43

我正在使用以下代码获取目录中的图像列表:

$files = scandir($imagepath);

$files也包括隐藏文件。我怎样才能排除它们?

4

11 回答 11

79

在 Unix 上,您可以使用preg_grep过滤掉以点开头的文件名:

$files = preg_grep('/^([^.])/', scandir($imagepath));
于 2011-12-16T10:08:29.233 回答
6

我倾向于将 DirectoryIterator 用于这样的事情,它提供了一种忽略点文件的简单方法:

$path = '/your/path';
foreach (new DirectoryIterator($path) as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $file =  $path.$fileInfo->getFilename();
}
于 2011-12-16T10:08:56.413 回答
5
$files = array_diff(scandir($imagepath), array('..', '.'));

或者

$files = array_slice(scandir($imagepath), 2);

可能比

$files = preg_grep('/^([^.])/', scandir($imagepath));
于 2018-10-10T19:54:16.697 回答
4
function nothidden($path) {
    $files = scandir($path);
    foreach($files as $file) {
        if ($file[0] != '.') $nothidden[] = $file;
        return $nothidden;
    }
}

只需使用此功能

$files = nothidden($imagepath);
于 2015-02-04T19:18:09.657 回答
1

我遇到了来自 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 操作系统。

于 2015-02-23T19:04:40.513 回答
1

我认为因为您正在尝试“过滤”隐藏文件,这样做更有意义并且看起来最好......

$items = array_filter(scandir($directory), function ($item) {
    return 0 !== strpos($item, '.');
});

我也不会调用该变量$files,因为它暗示它只包含文件,但实际上您也可以获取目录......在某些情况下:)

于 2017-01-02T03:19:07.020 回答
1

使用 preg_grep 排除带有特殊字符的文件名,例如

$dir = "images/";
$files = preg_grep('/^([^.])/', scandir($dir));

http://php.net/manual/en/function.preg-grep.php

于 2017-05-06T18:38:23.403 回答
0

假设隐藏文件以 a 开头,.您可以在输出时执行以下操作:

foreach($files as $file) {
    if(strpos($file, '.') !== (int) 0) {
        echo $file;
    }
}

现在您检查每个项目是否没有.作为第一个字符,如果没有,它会像您一样回应您。

于 2011-12-16T10:08:19.210 回答
0

scandir()是一个内置函数,如果您的目录只有 . & .. 隐藏文件然后尝试选择文件

$files = array_diff(scandir("path/of/dir"),array(".","..")) //can add other hidden file if don't want to consider

于 2020-06-23T14:28:20.760 回答
0

如果您也想重置数组索引并设置顺序,请使用以下代码:

$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)));
于 2018-04-18T09:53:03.913 回答
-1

我仍在为 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>";
}
于 2012-07-04T15:44:44.997 回答