PHP function to traverse all files in a directory

WBOY
Release: 2016-07-25 09:00:22
Original
948 people have browsed it
PHP traverses all files in a certain directory and provides two implementation methods. Friends in need may wish to refer to it.

Method 1, use dir to return the object. Method 2, use the readdir() function.

The following is the complete code:

<?php
/**
* 目录递归函数 dir返回对象
* site bbs.it-home.org
*/
function tree($directory) 
{ 
 $mydir = dir($directory); 
 echo "<ul>\n"; 
 while($file = $mydir->read())
 { 
  if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!="..")) 
  {
   echo "<li><font color=\"#ff00cc\"><b>$file</b></font></li>\n"; 
   tree("$directory/$file"); 
  } 
  else 
  echo "<li>$file</li>\n"; 
 } 
 echo "</ul>\n"; 
 $mydir->close(); 
} 
//开始运行

echo "<h2>目录为粉红色</h2><br>\n"; 
tree("./jbxue.com"); 

/**
* 方法2 用readdir()函数
*/
function listDir($dir)
{
 if(is_dir($dir))
    {
      if ($dh = opendir($dir)) 
  {
         while (($file = readdir($dh)) !== false)
   {
        if((is_dir($dir."/".$file)) && $file!="." && $file!="..")
    {
         echo "<b><font color='red'>文件名:</font></b>",$file,"<br><hr>";
         listDir($dir."/".$file."/");
        }
    else
    {
            if($file!="." && $file!="..")
     {
             echo $file."<br>";
          }
        }
         }
         closedir($dh);
      }
    }
}
//开始运行
listDir("./jbxue.com");
?>
Copy after login
Attached is the code for traversing all files in the directory.
<?php
   $num=0;    //记录目录下的文件个数
   $dirname='LAMP'; //要遍历的目录名字
   $dir_handle=opendir($dirname);

   echo '<table border="1" align="center" width="960px" cellspacing="0" cellpadding="0">';
   echo '<caption><h2>目录'.$dirname.'下面的内容</h2></caption>';
   echo '<tr align="left" bgcolor="#cccccc">';
   echo '<th>文件名</th><th>文件大小</th><th>文件类型</th><th>修改时间</th></tr>';
   while($file=readdir($dir_handle))
   {
   	 if($file!="."&&$file!="..")
   	 {
   	 	$dirFile=$dirname."/".$file;
   	 	if($num++%2==0)    //隔行换色
   	 		$bgcolor="#ffffff";
   	 	else 
   	 		$bgcolor="#cccccc";
   	 	echo '<tr bgcolor='.$bgcolor.'>';
   	 	echo '<td>'.$file.'</td>';
   	 	echo '<td>'.filesize($dirFile).'</td>';
   	 	echo '<td>'.filetype($dirFile).'</td>';
   	 	echo '<td>'.date("Y/n/t",filemtime($dirFile)).'</td>';
   	 	echo '</tr>';
   	 }
   }
   echo '</table>';
   closedir($dir_handle);
   echo '在<b>'.$dirname.'</b>目录下的子目录和文件共有<b>'.$num.'</b>个';
?>
Copy after login


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