Method One: Use Dir () to traverse the directory
Dir () function, returning a directory class instance when successful
The PHP dir () syntax format is:
Dir (directory)//directory the name of the directory where the file name needs to be displayed, including path information
PHP dir () Use example: List all the file names under the upload directory:
The code is as follows |
|
<?php $dir = @ Dir ("upload");//open upload directory; "@" to mask error messages, because sometimes you need to display files in the directory does not have files, at this time may be reported errors, with "@" to hide the error Enumerate all the files in the upload directory while (($file = $dir->read ())!== false) { echo "FileName:". $file. "<br/>"; } $dir->close (); ?> |
The output results are:
Filename:.
Filename:..
FileName: logo.gif
FileName: arrow.gif
FileName: bg.gif
Example
code is as follows |
&nbs P; |
Function tree ($dir) { $mydir = Dir ($di R); while ($file = $mydir->read ()) { & nbsp; 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 '); |
Method two uses Readir () to traverse the directory
Definitions and usage
The Readdir () function returns an entry in a table of contents handle opened by Opendir ().
If successful, the function returns a filename, otherwise it returns false.
Grammar
Readdir (Dir_stream)
Example
The code is as follows |
|
header (' Content-type:text/html;charset=utf-8 ');
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 '); |