Home > Backend Development > PHP Tutorial > Two commonly used methods to recursively delete folders in PHP

Two commonly used methods to recursively delete folders in PHP

墨辰丷
Release: 2023-03-31 15:12:02
Original
2294 people have browsed it

This article mainly introduces the method of recursively deleting specified folders in PHP. The example summarizes two commonly used techniques for recursively deleting folders. It is of great practical value. Friends who need it can refer to this article.

The example summarizes two methods of recursively deleting specified folders in PHP. The details are as follows:

Method one:

function recursiveDelete($dir)
{ 
  if ($handle = @opendir($dir))
  {
  while (($file = readdir($handle)) !== false)
  {
   if (($file == ".") || ($file == ".."))
   {
    continue;
   }
   if (is_dir($dir . '/' . $file))
   {
    // call self for this directory
    recursiveDelete($dir . '/' . $file);
   }
   else
   {
    unlink($dir . '/' . $file); // remove this file
   }
  }
  @closedir($handle);
  rmdir ($dir);
  }
}
Copy after login

Method two:

/*
 自定义的删除函数,可以删除文件和递归删除文件夹
*/
 function my_del($path)
{
 if(is_dir($path))
 {
   $file_list= scandir($path);
   foreach ($file_list as $file)
   {
    if( $file!='.' && $file!='..')
    {
     my_del($path.'/'.$file);
    }
   }
   @rmdir($path);
   //这种方法不用判断文件夹是否为空,
   //因为不管开始时文件夹是否为空,到达这里的时候,都是空的  
 }
 else
 {
  @unlink($path);
  //这两个地方最好还是要用@屏蔽一下warning错误,看着闹心
 }
}
$path='d:/技术文档 - 副本';
//要删除的文件夹
//如果php文件不是ANSI,而是UTF-8模式,
//而且要删除的文件夹中包含汉字字符的话,调用函数前需要转码
//$path=iconv( 'utf-8', 'gb2312',$path );
my_del($path);
Copy after login

Summary: The above is the entire content of this article, I hope it can be helpful to everyone learning helps.

Related recommendations:

php operates Excel files with Chinese content and exports files

php passed Serial port to realize the idea of ​​sending text messages and the specific implementation

php defines, traverses and deletes arrays

The above is the detailed content of Two commonly used methods to recursively delete folders in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template