Directory traversal is a PHP design often used in a function, many PHP projects have this function module. Today in this article to illustrate the example of PHP using a custom function to traverse all the files in the directory method. The specific methods are as follows:
Method One: Use Readir () to traverse the directory
The implementation code is as follows:
function Listdir ($dir)
{
if (Is_dir ($dir))
{
if ($handle = Opendir ($dir))
{while
($file = Readdir ($handle))
{
if ($file!= '. ' && $file!= ' ... ')
{
if (Is_dir, $dir. Directory_separator. $file))
{
echo ' directory name: '. $dir. Directory_separator. ' <font color= "Red" > '. $file. ' </font><br/> ';
Listdir ($dir. Directory_separator. $file);
else{
echo ' filename: '. $dir. Directory_separator. $file. ' <br/> ';
}
}}} Closedir ($handle);
else{
Echo ' is not a valid directory! '}
}
Listdir ('./phpmyadmin ');
Method Two: Use Dir () to traverse the directory
This example uses the Dir () function traversal to return a directory class instance when the execution succeeds
function tree ($dir)
{
$mydir = dir ($dir);
while ($file = $mydir->read ())
{
if ($file!= '. ' && $file!= ' ... ')
{
if (Is_dir ("$dir/$file"))
{
echo ' directory name: '. $dir. Directory_separator. ' <font color= "Red" > '. $file. ' </font><br/> ';
Tree ("$dir/$file");
else{
echo ' filename: '. $dir. Directory_separator. $file. ' <br/> ';
}
}} $mydir->close ();
}
Tree ('./phpmyadmin ');
In addition, there are many ways to achieve directory traversal, I believe the method described in this article can give you some help in PHP program design.