自己写的一个PHP文件目录检索代码,可递归搜索所有子目录或只列出当前目录。
注:本例只会以一维数组的形式列出所有文件/文件夹,不会以多维数组的形式树形列出。
直接上代码
/** * 获取指定路径下的文件列表,如果第二个参数为true, * 则会递归的列出子目录下的文件 * @param String $dir 目录 * @param String $recursion */ public static function getFileList($dir, $recursion = false){ $filelist = array(); $real_path = realpath($dir); if (is_dir($real_path)) { if ($dh = opendir($real_path)) { while (($file = readdir($dh)) !== false) { if (strpos($file, '.') === 0) { continue; } $full_path = $real_path . DIRECTORY_SEPARATOR . $file; $filetype = filetype($full_path); $is_dir = $filetype == 'dir'; $relative_path = str_ireplace(BASEPATH, '', $full_path); $relative_path = str_replace('', '/', $relative_path); $filelist[] = array( 'name'=>$file, 'path'=>$full_path, 'relative_path'=>$relative_path, 'is_dir'=>$is_dir, ); if($is_dir == true && $recursion == true){ $subdir = self::getFileList($real_path . DIRECTORY_SEPARATOR . $file, true); $filelist = array_merge($filelist, $subdir); } } closedir($dh); } } return $filelist; }
例如
print_r(Helper_File::getFileList('./'));
得到如下数组
Array ( [0] => Array ( [name] => config [path] => D:xampphtdocsminglsjy.hptrunkconfig [relative_path] => /config [is_dir] => 1 ) [1] => Array ( [name] => root.txt [path] => /home/evilfox9e6vqi3lnf6ozx/wwwroot/root.txt [relative_path] => /root.txt [is_dir] => ) [2] => Array ( [name] => uploads [path] => /home/evilfox9e6vqi3lnf6ozx/wwwroot/uploads [relative_path] => /uploads [is_dir] => 1 ) [3] => Array ( [name] => favicon.ico [path] => /home/evilfox9e6vqi3lnf6ozx/wwwroot/favicon.ico [relative_path] => /favicon.ico [is_dir] => ) )