Introduction to the use of php directory traversal and delete functions

  • 2020-06-01 08:38:02
  • OfStack

This site has nothing to write today directory to close the function

Includes traversing the folder under the file, directory subdirectory to read the current file under the directory and file delete the current folder under the directory subdirectory and the file above three functions currently do not support the Chinese file Chinese directory


<?php
header("Content-type:text/html;charset=utf-8");
/**
*  Reads files and directories in the current directory 
* 
* @param    string    $path     The path 
* @return    array     All files that meet the criteria 
*/
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 " Directories have :".implode("<br />",$arr['dir'])."<br />";
    echo " The file has :".implode("<br />",$arr['file']);
}
/**
*  Walk through the files and directories in the current directory and the directories in the subfolders 
* 
* @param    string    $path     The path 
* @return    array     All files that meet the criteria 
*/
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  The path 
* #return string  Delete successful return true  Failure to return false;
*/
function dirDel($path){
    if(!is_dir($path)){
        throw new Exception($path." You did not enter a valid directory ");
    }
    $hand = opendir($path);
    while(($file = readdir($hand))!==false){
        if($file=="."||$file=="..")  continue;
        if(is_dir($path."/".$file)){
            dirDel($path."/".$file);
        }else{
            @unlink($path."/".$file);
        }

    }
    closedir($hand);
    @rmdir($path);
}
?>


Related articles: