获取当前目录下指定类型文件列表
获取当前目录下指定类型文件列表,比如或者txt文件,jpg文件等等。
应用案例
$url="D:/wwwroot/ytecn.com/txt/"; $list=GetFilesInDir($url,'txt'); print_r($list);
输出结果为:
Array ( [1] => D:/wwwroot/ytecn.com/txt/1.txt [2] => D:/wwwroot/ytecn.com/txt/2.txt )
函数
// @param string $dir 目录 // @param string $type 文件类型,以|分隔 // @return array 文件列表 function GetFilesInDir($dir, $type) { $files = array(); $dir = str_replace('\\', '/', $dir); if (substr($dir, -1) !== '/') { $dir .= '/'; } if (!is_dir($dir)) { return array(); } if (function_exists('scandir')) { foreach (scandir($dir) as $f) { if ($f != "." && $f != ".." && is_file($dir . $f)) { foreach (explode("|", $type) as $t) { $t = '.' . $t; $i = strlen($t); if (substr($f, -$i, $i) == $t) { $sortname = substr($f, 0, (strlen($f) - $i)); $files[$sortname] = $dir . $f; break; } } } } } else { $handle = opendir($dir); if ($handle) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { if (is_file($dir . $file)) { foreach (explode("|", $type) as $t) { $t = '.' . $t; $i = strlen($t); if (substr($file, -$i, $i) == $t) { $sortname = substr($file, 0, (strlen($file) - $i)); $files[$sortname] = $dir . $file; break; } } } } } closedir($handle); } } return $files; }