Home >Backend Development >PHP Tutorial >PHP customizes dir(), readdir() functions to traverse all files in a directory_PHP tutorial
Method 1: Use dir() to traverse the directory
The dir() function returns a Directory class instance when successful
PHP dir() syntax format is:
dir(directory);//directory is the name of the directory where the file name needs to be displayed, and can contain path information
PHP dir() Usage example: List all file names in the upload directory:
代码如下 | |
$dir = @ dir("upload");//打开upload目录;“@”可屏蔽错误信息,因有时候需要显示文件的目录内并没有文件,此时可能会报出错误,用“@”隐藏掉错误 //列举upload目录中的所有文件 while (($file = $dir->read()) !== false) { echo "文件名: " . $file . " "; } $dir->close(); ?> |
The output result is:
File name: .
File name: ..
File name: logo.gif
File name: arrow.gif
File name: bg.gif
Example
代码如下 | |
function tree($dir) { $mydir = dir($dir); while($file = $mydir->read()) { if($file != '.' && $file != '..') { if(is_dir("$dir/$file")) { echo '目录名:'.$dir.DIRECTORY_SEPARATOR.''.$file.' '; tree("$dir/$file"); }else{ echo '文件名:'.$dir.DIRECTORY_SEPARATOR.$file.' '; } } } $mydir->close(); } tree('./phpmyadmin'); |
Method 2 Use readir() to traverse the directory
Definition and usage
The readdir() function returns the entry in the directory handle opened by opendir().
If successful, the function returns a file name, otherwise it returns false.
Grammar
readdir(dir_stream)
Example
代码如下 | |
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 '目录名:'.$dir.DIRECTORY_SEPARATOR.''.$file.' '; listDir($dir.DIRECTORY_SEPARATOR.$file); }else{ echo '文件名:'.$dir.DIRECTORY_SEPARATOR.$file.' '; } } } } closedir($handle); }else{ echo '非有效目录!'; } } listDir('./phpmyadmin'); |