Home > php教程 > php手册 > php遍历所有文件及文件夹的方法深入解析

php遍历所有文件及文件夹的方法深入解析

WBOY
Release: 2016-06-13 11:50:21
Original
963 people have browsed it

 1.方法一:

复制代码 代码如下:



$dir="D:";
static $dir_list =0;
static $file_list =0;
function listfile($dir){
global $dir_list,$file_list;
$d = dir($dir);
while ( $entry = $d->read()) {
$tem_curnt=$dir."/".$entry;
if($entry=="." || $entry=="..") continue;
if ( is_dir( $tem_curnt)) {
listfile($tem_curnt);
echo "文件夹 ".$tem_curnt."
";
$dir_list++;
}
elseif ( is_file($tem_curnt)) {
echo "文件".$tem_curnt."
";
$file_list++;
}
}
$d->close();
}
listfile($dir);
echo "目录数:".$dir_list;
echo"
";
echo"文件数:".$file_list;
?>


2.方法二:

复制代码 代码如下:


function list_dir($dirpath){
 if($dirpath[strlen($dirpath)]-1!='/'){
  $dirpath.="/";
 }
 static $result_array=array();
 if(is_dir($dirpath)){
  $files_dirs=scandir($dirpath);
  foreach($files_dirs as $file){
   if($file=='.'||$file=='..'){continue;}
   if(is_dir($dirpath.$file)){
    list_dir($dirpath.$file);
   }else{
    array_push($result_array,$dirpath.$file);
   }
  }
 }
 return $result_array;
}
$array=list_dir('D:/www');
foreach($array as $value){
 echo $value;
 echo "
";
}
?>


3.方法三:

复制代码 代码如下:


 function list_dir($dirpath){
  if($dirpath[strlen($dirpath)-1]!="//"){$dirpath.="//";}
  static $result_array=array();
  if(is_dir($dirpath)){
   $handle=opendir($dirpath);
   while($file=readdir($handle)){
    if($file=="."||$file==".."){continue;}
    if(is_dir($dirpath.$file)){
     list_dir($dirpath.$file."//");
    }else{
     array_push($result_array,$dirpath.$file);
    }
   }
   closedir($handle);
  }
  return $result_array;
 }
 $array=list_dir("D:/www");
 foreach($array as $value){
  echo $value;
  echo "
";
 }
?>


4.方法四:

复制代码 代码如下:


 function list_dir($dirpath){
  if($dirpath[strlen($dirpath)-1]!="//"){$dirpath.="//";}
  static $result_array=array();
  if(is_dir($dirpath)){
   $dir=dir($dirpath);
   while($file=$dir->read()){
    if($file=="."||$file==".."){continue;}
    if(is_dir($dirpath.$file)){
     list_dir($dirpath.$file."//");
    }else{
     array_push($result_array,$dirpath.$file);
    }
   }
   $dir->close();
  }
  return $result_array;
 }
 $array=list_dir("D:/www");
 foreach($array as $value){
  echo $value;
  echo "
";
 }
?>


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template