Home  >  Article  >  Backend Development  >  How to delete all directories and files in a specified directory in PHP, _PHP tutorial

How to delete all directories and files in a specified directory in PHP, _PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:06:16683browse

PHP method to delete all directories and files in a specified directory,

The example in this article describes how to delete all directories and files in the specified directory with PHP. Share it with everyone for your reference. The specific implementation method is as follows:

<&#63;php
/*
 * 
 * 删除指定目录中的所有目录及文件(或者指定文件)
 * 可扩展增加一些选项(如是否删除原目录等)
 * 删除文件敏感操作谨慎使用
 * @param $dir 目录路径
 * @param array $file_type指定文件类型
 */
function delFile($dir,$file_type='') { 
  if(is_dir($dir)){
    $files = scandir($dir);
 //打开目录 //列出目录中的所有文件并去掉 . 和 .. 
    foreach($files as $filename){
      if($filename!='.' && $filename!='..'){
        if(!is_dir($dir.'/'.$filename)){
          if(empty($file_type)){
            unlink($dir.'/'.$filename);
          }else{
            if(is_array($file_type)){
              //正则匹配指定文件
              if(preg_match($file_type[0],$filename)){
                unlink($dir.'/'.$filename);
              }
            }else{
              //指定包含某些字符串的文件
              if(false!=stristr($filename,$file_type)){
                unlink($dir.'/'.$filename);
              }
            }
          }
        }else{ 
          delFile($dir.'/'.$filename);
          rmdir($dir.'/'.$filename);
        } 
      }
    }
  }else{
    if(file_exists($dir)) unlink($dir);
  } 
}
delFile(dirname(__FILE__),'html');

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/960706.htmlTechArticleHow to delete all directories and files in the specified directory using PHP. This article describes how to delete all directories and files in the specified directory using PHP. Directory and file methods. Share it with everyone for your reference. Specific actual...
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