Home > Article > Backend Development > PHP gets files in directory
This article mainly introduces PHP to obtain files in the directory. Interested friends can refer to it. I hope it will be helpful to everyone.
1. Get the files in the directory, excluding subdirectories
//获取某目录下所有文件、目录名(不包括子目录下文件、目录名) $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 the files in the directory All files, including subdirectories
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; } } function get_filenamesbydir($dir){ $files = array(); get_allfiles($dir,$files); return $files; } $filenames = get_filenamesbydir("static/image/"); //打印所有文件名,包括路径 foreach ($filenames as $value) { echo $value."<br />"; }
Summary: The above is the entire content of this article, I hope it can be useful for everyone’s learning help.
Related recommendations:
php method to obtain the file suffix name
PHP image verification code class file source code sharing
##Detailed explanation of PHP session session processing function examples
The above is the detailed content of PHP gets files in directory. For more information, please follow other related articles on the PHP Chinese website!