简体   繁体   English

php使用scandir获取文件夹内容

[英]php using scandir to get folder contents

I am currently using scandir to get the contents of an upload folder. 我当前正在使用scandir获取上载文件夹的内容。 Here is my code specifying the directory: 这是我指定目录的代码:

$dir    = /var/www/vhosts/mywebsite.com/httpdocs/admin/newsletters/1234-16-10-2013/
$files = scandir($dir);

I then loop through the results like this: 然后,我遍历如下结果:

foreach($files as $file) {

  echo '<option value="'.$file.'">'.$file.'</option>';    

}

The above works fine and populates my select menu correctly. 上面的工作正常,并正确填充我的选择菜单。 However for some reason the options in the select menu look like this: 但是由于某些原因,选择菜单中的选项如下所示:

<option value=".">.</option>
<option value="..">..</option>
<option selected="selected" value="header.jpg">header.jpg</option>
<option value="sale.jpg">sale.jpg</option>
<option value="show-now.jpg">show-now.jpg</option>

The first 2 options contains full stops. 前两个选项包含句号。 The first has 1 and the second has 2. 第一个具有1,第二个具有2。

Does anyone know why this is? 有人知道为什么是这样吗? Is it because of the depth of the directory? 是因为目录的深度吗?

Any help would be greatly appreciated! 任何帮助将不胜感激!

That's because of system entries . 那是因为系统条目. and .. which are pointers to 'current directory' and 'parent directory'. ..指向“当前目录”和“父目录”的指针。 You'll need to filter them if you don't want to see them in your output. 如果您不想在输出中看到它们,则需要对其进行过滤。

You may want to filter your entries with is_file() - then . 您可能需要使用is_file() -then过滤条目. and .. would be skipped since they are actually directories (pointers to them) ..将被跳过,因为它们实际上是目录(指向它们的指针)

Scandir is relatively slow. Scandir相对较慢。

        foreach (new DirectoryIterator($path) as $file)
        {
            if($file->isDot()) continue;

            if($file->isDir()))
            {
                print $file->getFilename() . '<br />';
            }
        }

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

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