PHP Directory Files: Iterate & List Guide
In PHP, you can use the scandir() function to list files in a folder.
Below is a straightforward example:
$dir = "path/to/directory";
// 打开目录
if (is_dir($dir)){
if ($dh = opendir($dir)){
// 读取目录中的文件
while (($file = readdir($dh)) !== false){
echo "filename: $file : filetype: " . filetype($dir . $file) . "<br>";
}
// 关闭目录
closedir($dh);
}
}
In the example above, the is_dir() function is first used to check if the specified directory exists. Then, the opendir() function is used to open the directory, the readdir() function is used to read the files in the directory, and the filetype() function is used to get the file types. Finally, the closedir() function is used to close the directory.
Please replace path/to/directory with the path of the directory you want to traverse.