Home > Article > Backend Development > Introduction to the use of php directory traversal and deletion functions_PHP tutorial
The editor had nothing to do today and wrote the function that I want to close the directory.
Including traversing the files, directories and subdirectories under the folder, reading the directories and files under the current file, and deleting the directories, subdirectories and files under the current folder. Chinese files and Chinese directories are not currently supported
header("Content-type: text/ html;charset=utf-8");
/**
* Read files and directories in the current directory
*
* @param string $path Path
* @return array All files that meet the conditions
*/
function tlist($path){
$path = iconv('utf-8', 'gbk', $ path);
if(!is_dir($path)){
throw new Exception($path."Not a directory");
}
$arr = array('dir'=> array(),'file'=>array());
$hd = opendir($path);
while(($file = readdir($hd))!==false){
If($file=="."||$file=="..") {continue;}
if(is_dir($path."/".$file)){
$arr[ 'dir'][] = iconv('gbk','utf-8',$file);
}else if(is_file($path."/".$file)){
$arr[ 'file'][] = iconv('gbk','utf-8',$file);
}
}
closedir($hd);
echo "The directory contains:". implode("
",$arr['dir'])."
";
echo "The files are:".implode("
", $arr['file']);
}
/**
* Traverse the files and directories in the current directory and directories in subfolders
*
* @param string $path Path
* @return array All files that meet the conditions
*/
function blist($path){
if(!is_dir(iconv("utf-8", "gbk",$path))){
throw new Exception("Folder".$path."Does not exist or is not a file");
}
$arr = array();
$hd = opendir(iconv("utf-8","gbk",$path));
while(($file = readdir($hd))!==false){
if($ file=="."||$file=="..") {continue;}
$newpath=iconv('utf-8', 'gbk', $path) .'/'.$file;
if(is_dir($newpath)){
$arr[] = blist($path."/".$file);
}else if(is_file($newpath)){
$arr[] = iconv('gbk','utf-8',$file);
}
}
closedir($hd);
return $arr;
}
/**
* Delete files and subdirectories in the directory
* #param string $path path
* #return string Returns true if the deletion is successful and false if it fails;
*/
function dirDel($path){
if(!is_dir($path)){
throw new Exception($path."The input is not a valid directory" );
}
$hand = opendir($path);
while(($file = readdir($hand))!==false){
if($file==". "||$file=="..") continue;
if(is_dir($path."/".$file)){
dirDel($path."/".$file);
}else{
);
}
?>