遍历指定目录下的文件
作者:杨锦龙时间:2025-10-16点击量:0次
/**
* 扫描目录下的文件和子目录(排除 . 和 ..)
* @param string $path 目录路径
* @return array 文件/目录名列表,失败返回空数组
*/
public function scanDirFileList($path)
{
$list = [];
// 检查路径是否为空
if (empty($path)) {
trigger_error("Invalid path: path is empty.", E_USER_WARNING);
return $list;
}
// 检查目录是否存在且为目录
if (!is_dir($path)) {
//trigger_error("Invalid path: '{$path}' is not a valid directory.", E_USER_WARNING);
return $list;
}
// 检查是否可读
if (!is_readable($path)) {
trigger_error("Permission denied: Cannot read directory '{$path}'.", E_USER_WARNING);
return $list;
}
$temp_list = scandir($path);
if ($temp_list === false) {
//trigger_error("Failed to scan directory: '{$path}'.", E_USER_WARNING);
return $list;
}
foreach ($temp_list as $file) {
// 排除当前目录和上级目录
if ($file === '.' || $file === '..') {
continue;
}
$list[] = $file;
}
return $list;
}
/**
* 扫描目录,可选是否包含隐藏文件(以 . 开头的文件)
* @param string $path 目录路径
* @param bool $includeHidden 是否包含隐藏文件(默认 false)
* @return array
*/
public function scanDirFileHiddenList($path, $includeHidden = false)
{
$list = [];
if (empty($path) || !is_dir($path) || !is_readable($path)) {
trigger_error("Invalid or unreadable directory: {$path}", E_USER_WARNING);
return $list;
}
$temp_list = scandir($path);
if ($temp_list === false) return $list;
foreach ($temp_list as $file) {
if ($file === '.' || $file === '..') continue;
if (!$includeHidden && substr($file, 0, 1) === '.') continue; // 过滤隐藏文件
$list[] = $file;
}
return $list;
}
/**
* 返回文件详细信息
* @param string $path
* @return array ['name' => '...', 'type' => 'file|dir', 'path' => '...']
*/
public function scanDirFileDetailList($path)
{
$list = [];
if (empty($path) || !is_dir($path) || !is_readable($path)) {
trigger_error("Invalid or unreadable directory: {$path}", E_USER_WARNING);
return $list;
}
$temp_list = scandir($path);
if ($temp_list === false) return $list;
$realPath = rtrim($path, '/\\'); // 标准化路径
foreach ($temp_list as $file) {
if ($file === '.' || $file === '..') continue;
$fullPath = $realPath . DIRECTORY_SEPARATOR . $file;
$list[] = [
'name' => $file,
'type' => is_dir($fullPath) ? 'dir' : 'file',
'path' => $fullPath,
'size' => is_file($fullPath) ? filesize($fullPath) : null,
'mtime' => filemtime($fullPath)
];
}
return $list;
}