我正在使用以下代码获取目录中的图像列表:
$files = scandir($imagepath);
但$files
也包括隐藏文件。我怎样才能排除它们?
我正在使用以下代码获取目录中的图像列表:
$files = scandir($imagepath);
但$files
也包括隐藏文件。我怎样才能排除它们?
在 Unix 上,您可以使用preg_grep
过滤掉以点开头的文件名:
$files = preg_grep('/^([^.])/', scandir($imagepath));
我倾向于将 DirectoryIterator 用于这样的事情,它提供了一种忽略点文件的简单方法:
$path = '/your/path';
foreach (new DirectoryIterator($path) as $fileInfo) {
if($fileInfo->isDot()) continue;
$file = $path.$fileInfo->getFilename();
}
$files = array_diff(scandir($imagepath), array('..', '.'));
或者
$files = array_slice(scandir($imagepath), 2);
可能比
$files = preg_grep('/^([^.])/', scandir($imagepath));
function nothidden($path) {
$files = scandir($path);
foreach($files as $file) {
if ($file[0] != '.') $nothidden[] = $file;
return $nothidden;
}
}
只需使用此功能
$files = nothidden($imagepath);
我遇到了来自 php.net 的评论,专门针对 Windows 系统: http: //php.net/manual/en/function.filetype.php#87161
出于存档目的在此处引用:
我在 Windows Vista 上使用 CLI 版本的 PHP。以下是如何确定文件是否被 NTFS 标记为“隐藏”:
function is_hidden_file($fn) { $attr = trim(exec('FOR %A IN ("'.$fn.'") DO @ECHO %~aA')); if($attr[3] === 'h') return true; return false; }
更改
if($attr[3] === 'h')
为if($attr[4] === 's')
将检查系统文件。这应该适用于任何提供 DOS shell 命令的 Windows 操作系统。
我认为因为您正在尝试“过滤”隐藏文件,这样做更有意义并且看起来最好......
$items = array_filter(scandir($directory), function ($item) {
return 0 !== strpos($item, '.');
});
我也不会调用该变量$files
,因为它暗示它只包含文件,但实际上您也可以获取目录......在某些情况下:)
使用 preg_grep 排除带有特殊字符的文件名,例如
$dir = "images/";
$files = preg_grep('/^([^.])/', scandir($dir));
假设隐藏文件以 a 开头,.
您可以在输出时执行以下操作:
foreach($files as $file) {
if(strpos($file, '.') !== (int) 0) {
echo $file;
}
}
现在您检查每个项目是否没有.
作为第一个字符,如果没有,它会像您一样回应您。
scandir()是一个内置函数,如果您的目录只有 . & .. 隐藏文件然后尝试选择文件
$files = array_diff(scandir("path/of/dir"),array(".","..")) //can add other hidden file if don't want to consider
如果您也想重置数组索引并设置顺序,请使用以下代码:
$path = "the/path";
$files = array_values(
preg_grep(
'/^([^.])/',
scandir($path, SCANDIR_SORT_ASCENDING)
));
一条线:
$path = "daten/kundenimporte/";
$files = array_values(preg_grep('/^([^.])/', scandir($path, SCANDIR_SORT_ASCENDING)));
我仍在为 seegee 的解决方案留下复选标记,我会在下面发表评论,以便对他的解决方案进行轻微修正。
他的解决方案屏蔽了目录(. 和 ..),但不屏蔽隐藏文件,如 .htaccess
一个小的调整解决了这个问题:
foreach(new DirectoryIterator($curDir) as $fileInfo) {
//Check for something like .htaccess in addition to . and ..
$fileName = $fileInfo->getFileName();
if(strlen(strstr($fileName, '.', true)) < 1) continue;
echo "<h3>" . $fileName . "</h3>";
}