Home >Backend Development >PHP Tutorial >PHP traverse directories and files under directories_PHP tutorial

PHP traverse directories and files under directories_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:39837browse

There is such a requirement in the project that it is necessary to traverse all the files in a certain folder (directory). The following is the PHP code written to solve this problem, recorded here.

The first implementation method is to use dir to return the object, and the second implementation method is to use the readdir() function.

<?php
/**********************
一个简单的目录递归函数
第一种实现办法:用dir返回对象
***********************/
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("./bkjia"); 
?>
<?php
/***********************
第二种实现办法:用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("./bkjia");
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752438.htmlTechArticleThere is such a requirement in the project, which requires traversing all files in a certain folder (directory). The following is the PHP code written to solve this problem, recorded here. The first way to achieve...
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