search
HomeBackend DevelopmentPHP TutorialHow to use PHP to delete files recursively to achieve code summary

Introducing several PHP codes that use recursive deletion of files. I hope it will be helpful to friends in their PHP learning.

Loop + Recursion

<?php 
deltree(&#39;./复件 复件 复件 复件 复件 复件 复件 复件 aaa&#39;); 
function deltree($pathdir) 
{ 
//echo $pathdir.&#39;<br/>&#39;;//我调试时用的 
if(is_empty_dir($pathdir))//如果是空的 
{ 
rmdir($pathdir);//直接删除 
} 
else 
{//否则读这个目录,除了.和..外 
$d=dir($pathdir); 
while($a=$d->read()) //下只删除$pathdir下 
{ 
if(is_file($pathdir.&#39;/&#39;.$a) && ($a!=&#39;.&#39;) && ($a!=&#39;..&#39;)) 
{ 
unlink($pathdir.&#39;/&#39;.$a); //如果是文件就直接删除 
}elseif(is_dir($pathdir.&#39;/&#39;.$a) && ($a!=&#39;.&#39;) && ($a!=&#39;..&#39;)) //如果是目录 
{ 
if(!is_empty_dir($pathdir.&#39;/&#39;.$a))//是否为空 
{ 
deltree($pathdir.&#39;/&#39;.$a); //如果不是,调用自身 
}else 
{ 
rmdir($pathdir.&#39;/&#39;.$a); //如果是空就直接删除 
} 
} 
} 
$d->close(); 
//echo "必须先删除目录下的所有文件";//我调试时用的 
rmdir($pathdir); 
} 
} 
function is_empty_dir($pathdir) 
{ 
//判断目录是否为空,我的方法不是很好吧?除了.和..之外有其他东西不是为空 
$d=opendir($pathdir); 
$i=0; 
while($a=readdir($d)) 
{ 
$i++; 
} 
closedir($d); 
if($i>2){return false;} 
else return true; 
} 
?>

Recursive method

<?php 
header("Content-Type:text/html; charset=gb2312"); 
if(deleteDir(&#39;./复件 复件 复件 复件 复件 复件 复件 复件 复件 复件 复件 aaa&#39;)) 
echo "删除成功"; 
function deleteDir($dir) 
{ 
if (@rmdir($dir)==false && is_dir($dir)) //删除不了,进入删除所有文件 
{ 
if ($dp = opendir($dir)) 
{ 
while (($file=readdir($dp)) != false) 
{ 
if($file!=&#39;.&#39; && $file!=&#39;..&#39;) 
{ //echo $file=$dir.&#39;/&#39;.$file;echo &#39;<br/>&#39;; 
$file=$dir.&#39;/&#39;.$file; 
if (is_dir($file)) //是真实目录 
{ 
deleteDir($file); 
}else { 
unlink($file); 
} 
} 
} 
closedir($dp); 
}else 
{ 
return false; 
} 
} 
if (is_dir($dir) && @rmdir($dir)==false) //是目录删除不了 
return false; 
return true; 
} 
?>

Introducing two more recursive methods:

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

The above is the detailed content of How to use PHP to delete files recursively to achieve code summary. 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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.