search
HomeBackend DevelopmentPHP TutorialCode summary for php recursively creating and deleting folders_PHP tutorial

Code summary for php recursively creating and deleting folders_PHP tutorial

Jul 21, 2016 pm 03:19 PM
phpcodedeletecopyJianhefoldermethodgenerateofTable of contentskindrecursion

The first method:

Copy the code The code is as follows:

/**
* Directory generation class: UtilsMakeDir
* @author yepeng
* @since 2010.3.18
*/
class UtilsMakeDir{
//This directory will not be created when the base directory is created. This should be an existing directory
private static $makeBasePath = 'video';
private static $delBasePath = 'video';

/**
* Create the directory recursively,
* Return the full path if the creation is successful,
* Return false if the creation fails
* @param String $pathString Path string such as '2/3/4/5'
* @return false or string

public static function makeDir($pathString){
$pathArray = explode('/',$pathString);
if(empty($pathArray[0 ])){
return false;
}
$path = array_shift($pathArray);
self::$basePath = self::$basePath.'/'.$path;
if(is_dir(self::$basePath)){
$path = implode('/',$pathArray);
self::makeDir($path);
}
else{
@mkdir(self::$basePath,0777);
$path = implode('/',$pathArray);
self::makeDir($path);
}
if(is_dir(self::$basePath)){
return self::$basePath;
}
else{
return false;
}
}*/
/* *
* Create a directory, including the base directory. For example, if the picture is to be placed under video (video is the existing directory), the parameter you pass in should be video/2/3/4
* If the creation is successful, the full path will be returned. ,
* Return false if establishment fails
* @param String $pathString path string such as 'video/2/3/4/5'
* @return false or string
**/
public static function makeDir($pathString){
$pathArray = explode('/',$pathString);
$tmpPath = array_shift($pathArray);
foreach ($pathArray as $val){
$tmpPath .= "/".$val;
if(is_dir($tmpPath)){
continue;
}
else {
@mkdir($tmpPath,0777);
}
}
if(is_dir($tmpPath)){
return $tmpPath;
}
else{
return false;
}
} /**
* Recursive deletion
* Delete directories and files
* If you pass a path like 'video/2/3/4', all directories and files under 4 will be deleted
* @param string $ stringPath
*/
public static function delDir($stringPath){
if(!$handle = @opendir($stringPath)){
return false;
}
while (false !==($file = readdir($handle))){
if($file !='.' && $file != '..') {
$tmpdir = $stringPath."/".$file;
if(is_dir($tmpdir)){
self::delDir($tmpdir);
rmdir($tmpdir);
}
if(is_file($tmpdir)){
unlink($tmpdir);
}
}
}
closedir($handle);
} }
?>

Loop + recursion, successfully tested under winxp. As long as the php file is encoded as gb2312 and the file name is arbitrary, the file name should be changed to be encoded as gb2312 and it will be fine
Copy code The code is as follows:

deltree('./ copy copy copy copy copy copy copy copy copy aaa');
function deltree($pathdir)
{
//echo $pathdir.'
';//I use it when debugging
if(is_empty_dir($ pathdir))//If it is empty
{
rmdir($pathdir);//Delete directly
}
else
{//Otherwise read this directory, except . and .. Outer
$d=dir($pathdir);
while($a=$d->read()) //Only delete $pathdir Next
{
if(is_file($ pathdir.'/'.$a) && ($a!='.') && ($a!='..'))
{
unlink($pathdir.'/'.$a) ; //If it is a file, delete it directly
}elseif(is_dir($pathdir.'/'.$a) && ($a!='.') && ($a!='..')) / /If it is a directory
{
if(!is_empty_dir($pathdir.'/'.$a))//Is it empty
{
deltree($pathdir.'/'.$a ); //If not, call itself
}else
{
rmdir($pathdir.'/'.$a); //If it is empty, delete it directly
}
}
}
$d->close();
//echo "All files in the directory must be deleted first";//I use it when debugging
rmdir($pathdir);
}
}
function is_empty_dir($pathdir)
{
//Isn’t my method good for judging whether the directory is empty? There are other things besides . and .. Empty
$d=opendir($pathdir);
$i=0;
while($a=readdir($d))
{
$i++;
}
closedir($d);
if($i>2){return false;}
else return true;
}
?>

The second recursive method was tested successfully under winxp. As long as the PHP file is encoded as gb2312 and the file name is arbitrary, the file name should be changed to gb2312 and it will be fine. No test.
Copy code The code is as follows:

header("Content-Type:text/html; charset=gb2312");
if(deleteDir('./ copy copy copy copy copy copy copy copy copy copy copy Copy aaa'))
echo "Delete successfully";
function deleteDir($dir)
{
if (@rmdir($dir)==false && is_dir($dir)) // Cannot delete, go to delete all files
{
if ($dp = opendir($dir))
{
while (($file=readdir($dp)) != false)
{
if($file!='.' && $file!='..')
{ //echo $file=$dir.'/'.$file;echo '
';
$file=$dir.'/'.$file;
if (is_dir($file)) //It is the real directory
{
deleteDir($file);
}else {
unlink($file);
}
}
}
closedir($dp);
}else
{
return false;
}
}
if (is_dir($dir) && @rmdir($dir)==false) //The directory cannot be deleted
return false;
return true;
}
?>

The third recursive method was successfully tested under winxp. It is very useful for listing directory files
Copy code The code is as follows:

function listDir($dir)
{
static $break=0; if($break++==100 ) exit;//Control the depth level
static $i=-0;
if(is_dir($dir))//Directory
{
if ($dh = opendir($dir) )//Open
{
while (($file = readdir($dh)) !== false)
{
if((is_dir($dir."/".$file) ) && $file!="." && $file!="..")//Directory
{
$j=$i;while($j--) echo "------ -";
echo "Directory name: ".$dir."/".$file."
";
$i++;
listDir($dir."/".$file);
$i--;
}
else
{
if($file!="." && $file!="..")
{
$j=$i;while($j--) echo "------ -";
$ext=trim(extend($file));
//if($ext=='jpg')
echo $dir.'/'.$file."";
}
}
}
closedir($dh);
}
}
}
function extend($file_name)
{
$retval="";
$pt=strrpos($file_name, ".");
if ($pt) $retval=substr($file_name, $pt+1, strlen($file_name ) - $pt);
return ($retval);
}
//Start running
listDir(".");
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325352.htmlTechArticleFirst method: Copy the code as follows: ?php /*** Directory generation class: UtilsMakeDir * @author yepeng * @since 2010.3.18*/ class UtilsMakeDir{ / /base directory will not be used when creating a directory...
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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor