Hongmu Notes
Home Language Notes Check whether the directory exists; if it does, delete all files within the directory; if it does not, create the directory.
Language Notes PHP

Check whether the directory exists; if it does, delete all files within the directory; if it does not, create the directory.

Check whether the directory exists; if it does, delete all files within the directory; if it does not, create the directory.

You can use PHP's built-in functions. file_exists()is_dir() Check whether the directory exists. If it exists, you can use it. glob() The function retrieves all files in the directory and uses them. unlink() The function removes them. If the directory does not exist, it can be used. mkdir() Create a directory.

Here is an example code that implements the aforementioned functionality:

$dir = '/path/to/directory'; // 目录路径

if (file_exists($dir) && is_dir($dir)) {
  // 目录已存在,清空目录
  $files = glob($dir . '/*'); // 获取目录下的所有文件
  foreach ($files as $file) {
    if (is_file($file)) {
      unlink($file); // 删除文件
    }
  }
} else {
  // 目录不存在,创建目录
  mkdir($dir, 0777, true); // 创建目录
}

In this example,$dir The path to the variable storage directory. Use this first. file_exists()is_dir() Check whether the directory exists. If the directory exists, proceed. glob() The function retrieves all files in the directory and uses them. unlink() The function removes them. If the directory does not exist, use it. mkdir() The function creates a directory. mkdir() The second parameter in the function 0777 Specifies that all users are granted read, write, and execute permissions for the directory. The third parameter true This function recursively creates a directory; if the parent directory does not exist, it will also be created.

Encapsulating the above code into a function makes it more reusable and maintainable; below is an example of such encapsulation:

 隐藏内容:会员可查看
function clearOrCreateDirectory($dir) {
  if (file_exists($dir) && is_dir($dir)) {
    // 目录已存在,清空目录
    $files = glob($dir . '/*'); // 获取目录下的所有文件
    foreach ($files as $file) {
      if (is_file($file)) {
        unlink($file); // 删除文件
      }
    }
  } else {
    // 目录不存在,创建目录
    mkdir($dir, 0777, true); // 创建目录
  }
}

The parameter of this function is the path to the directory to be manipulated. When the function is called, it checks whether the directory exists; if it does, the directory is emptied; if it does not, the directory is created. You can call this function as follows:

clearOrCreateDirectory('/path/to/directory');

among /path/to/directory The path to the directory to be operated on.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 143
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 191
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(PC+WAP) High-end, sophisticated kitchenware website – pbootCMS template; Cabinet design website source code download – 0129

(PC+WAP) High-end, sophisticated kitchenware website – pbootCMS template; Cabinet design website source code download – 0129 Practical Collection pbootcms Template

This premium and sophisticated PbootCMS kitchenware and cabinetry design website template supports access via both PC and WAP devices. Its modern, understated luxury design style is ideal for showcasing kitchen appliances, integrated cabinetry solutions, and custom design proposals. It enables high-end kitchenware brands or cabinetry design companies to showcase their product aesthetics online and enhance their brand premium value. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin
👁 56
Responsive Home Bedding and Textile Products Website Template – 0927

Responsive Home Bedding and Textile Products Website Template – 0927 Practical Collection Yiyou template

An eYouCMS responsive website template designed for the home mattress and home textile products industry. Its warm and cozy design is ideal for showcasing mattress products, home textile collections, home decor combinations, and brand stories. This template helps home furnishing brands showcase their products online and attract household consumers. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYou...
👁 34
(PC+WAP) Laboratory Chemical Instrumentation Equipment Website Template 1094

(PC+WAP) Laboratory Chemical Instrumentation Equipment Website Template 1094 Practical Collection pbootcms Template

A PbootCMS website template for laboratory chemical instrumentation and equipment, compatible with both PC and WAP devices. Featuring a professional, tech-oriented design ideal for showcasing laboratory instruments, chemical equipment, and technical expertise. This template helps scientific instrument manufacturers showcase their products online and attract research and testing clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 38
(PC + WAP) PbootCMS website template for higher education institutions, colleges, and vocational schools; Download source code for government agencies and associations websites – 0130

(PC + WAP) PbootCMS website template for higher education institutions, colleges, and vocational schools; Download source code for government agencies and associations websites – 0130 Practical Collection pbootcms Template

A PbootCMS template designed for university websites, vocational school websites, and government association websites, supporting both PC and WAP devices. Its professional and sophisticated design effectively showcases the institution's identity, teaching achievements, and organizational functions. It is an ideal choice for universities or government agencies looking to create official portal websites. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: ww...
👁 45
Responsive premium ceramic tableware website template 0928

Responsive premium ceramic tableware website template 0928 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the premium ceramic tableware industry. Its elegant and sophisticated design style effectively showcases ceramic tableware products, design concepts, brand stories, and spatial arrangements. It helps ceramic brands showcase their products online and attract both household customers and gift-giving clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 49
(Adaptive Mobile Version) Explosion-Proof Control Box Website Template; Explosion-Proof Equipment Website Source Code – 1095

(Adaptive Mobile Version) Explosion-Proof Control Box Website Template; Explosion-Proof Equipment Website Source Code – 1095 Practical Collection pbootcms Template

An explosion-proof control box and explosion-proof equipment PbootCMS website template, compatible with both PC and WAP devices. The professional and secure design is ideal for showcasing explosion-proof control boxes, explosion-proof electrical appliances, and other products. This template enables explosion-proof equipment manufacturers to showcase their products online and attract customers from the petrochemical and industrial sectors. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 57