Home >Backend Development >PHP Tutorial >PHP code example to list all files in a directory
This article introduces an example code that uses PHP to list all files in a directory for your reference.
List all files in the directory, the code is as follows: <?php $current_dir = 'E:/temp/'; $dir = opendir($current_dir); echo "direcotry list:<ul>"; while(false !== ($file=readdir($dir))){ if($file != "." && $file != ".."){ echo "<li>$file</li>"; } } //by bbs.it-home.org echo "</ul>"; closedir($dir); ?> If the directory and the website are in the same partition, you can also use $current_dir='/temp/'; directly. The above is an example under Windows. Let’s look at a PHP example under Linux that lists all files in a directory. as follows: 1. Get the files in the directory, excluding subdirectories. <?php //获取某目录下所有文件、目录名(不包括子目录下文件、目录名) $handler = opendir($dir); while (($filename = readdir($handler)) !== false) {//务必使用!==,防止目录下出现类似文件名“0”等情况 if ($filename != "." && $filename != "..") { $files[] = $filename ; } } } closedir($handler); //打印所有文件名 foreach ($filens as $value) { echo $value."<br />"; } ?> 2. Get all files in the directory, including subdirectories. <?php function get_allfiles($path,&$files) { if(is_dir($path)){ $dp = dir($path); while ($file = $dp ->read()){ if($file !="." && $file !=".."){ get_allfiles($path."/".$file, $files); } } $dp ->close(); } if(is_file($path)){ $files[] = $path; } } //edit bbs.it-home.org function get_filenamesbydir($dir){ $files = array(); get_allfiles($dir,$files); return $files; } $filenames = get_filenamesbydir("static/image/"); //打印所有文件名,包括路径 foreach ($filenames as $value) { echo $value."<br />"; } ?> |