Home >Backend Development >PHP Tutorial >How to implement php to delete folders and files under a fixed path

How to implement php to delete folders and files under a fixed path

php中世界最好的语言
php中世界最好的语言Original
2018-05-19 10:11:171644browse

This time I will show you how to use PHP to delete folders and files under a fixed path, and how to use PHP to delete folders and files under a fixed path. What are the precautions? take a look.

is also suitable for clearing cache in thinkphp. In thinkphp, you can write the following code into the ./Application/Admin/Common/function.php file, and then call this function in

controller Perform cleanup operations.

Functions used:

scandir($path) Traverse all files in a folder and return an array. unlink($filename) Delete the file.
rmdir($path) Only delete empty folders

<?php
 //设置需要删除的文件夹
  $path = "./Application/Runtime/";
  //清空文件夹函数和清空文件夹后删除空文件夹函数的处理
  function deldir($path){
   //如果是目录则继续
   if(is_dir($path)){
    //扫描一个文件夹内的所有文件夹和文件并返回数组
   $p = scandir($path);
   foreach($p as $val){
    //排除目录中的.和..
    if($val !="." && $val !=".."){
     //如果是目录则递归子目录,继续操作
     if(is_dir($path.$val)){
      //子目录中操作删除文件夹和文件
      deldir($path.$val.'/');
      //目录清空后删除空文件夹
      @rmdir($path.$val.'/');
     }else{
      //如果是文件直接删除
      unlink($path.$val);
     }
    }
   }
  }
  }
 //调用函数,传入路径
 deldir($path);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

PHP uses asterisks to replace some characters in username mobile phone and email address

PHP decorator mode use case analysis

The above is the detailed content of How to implement php to delete folders and files under a fixed path. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn