简体   繁体   English

使用array_slice删除scandir点和点点条目是否安全?

[英]Is it safe to use array_slice to remove scandir dot and dot-dot entries?

I want to use array_slice with scandir in my PHP script. 我想在我的PHP脚本中使用带有scandir array_slice

Normal usage: 正常使用:

<?php

$files = scandir('/path/to/files');

foreach($files as $file) {
    if($file != '.' && $file != '..') {
        // Do something here...
    }
}

My example: 我的例子:

<?php

$files = array_slice(scandir('/path/to/files'), 2);

foreach($files as $file) {
    // Do something here...
}

My doubt is, is it safe or not to use this type of logic ? 我怀疑的是,使用这种逻辑是否安全?

It is definitely not safe. 这绝对不安全。 The following example creates a directory with a file called ! 以下示例使用名为!的文件创建目录! . When scandir sorts the results, ! 当scandir对结果进行排序时, ! appears before . 出现在之前. and .. : ..

mkdir('test');
touch('test/!');
print_r(scandir('test'));
unlink('test/!');
rmdir('test');

Output: 输出:

Array
(
    [0] => !
    [1] => .
    [2] => ..
)

In general, this will be an issue for all filenames starting with a character which sorts before . 通常,对于以之前排序的字符开头的所有文件名,这都是一个问题. . That includes some unprintable characters which probably won't exist in real world data, but it also applies to common punctuation including ! # $ % & ( ) + - 这包括一些可能在现实世界数据中不存在的不可打印的字符,但它也适用于常见的标点符号,包括! # $ % & ( ) + - ! # $ % & ( ) + - . ! # $ % & ( ) + -

Even if it worked, I wouldn't recommend it, as using array_slice there makes the intent of the code less clear. 即使它工作,我也不推荐它,因为使用array_slice会使代码的意图不那么清晰。

Instead of trying to scan directory by old-school ways, i strongly recommend using of SPL Directory Iterator for such requirement. 我强烈建议使用SPL Directory Iterator来满足此类要求,而不是尝试按照旧式方式扫描目录。

Try this: 试试这个:

$iterator = new \DirectoryIterator('/path/to/files');
foreach ($iterator as $file) {
    if($file->isDot()) {
        continue;
    }
    /** Now here you can use lot of SplFileInfo interface methods here */
    // $file->getFilename();
    // $file->isFile();
    // $file->isDir();
    // $file->getSize();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM