如何用PHP列出一个目录中的所有文件是最好的方式?是否有一个$_SERVER函数可以做到这一点?我想列出usernames/目录中的所有文件,并循环遍历结果以链接方式,以便我只需点击文件名的超链接即可进入该文件。谢谢!
$path = '/tmp';
$files = scandir($path);
下面的代码将从 scandir
返回的数组中删除 .
和 ..
:
$files = array_diff(scandir($path), array('.', '..'));
$files
而是 $filesAndDirs
。 - vladkras$files = array_diff(scandir(__DIR__ .$path), array('.', '..'));
解决了这个问题。参考来源:https://dev59.com/NWfWa4cB1Zd3GeqPdhh9 - Stack Underflowarray_values(array_diff(scandir($path), array('..', '.')));
- vinsa看看这个: readdir()
这段代码可以列出特定目录中的所有条目:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
编辑:miah的解决方案比我的更优雅,您应该使用他的解决方案。
$files = scandir($imgspath); $total = count($files); $images = array(); for($x = 0; $x <= $total; $x++): if ($files[$x] != '.' && $files[$x] != '..') { $images[] = $files[$x]; } endfor;
- Patrick Mutwiriglob()
函数! http://php.net/manual/en/function.glob.php - Peter Krauss.html
文件,而且不想要包含 404
的文件,你可以在一个循环中使用你的解决方案来实现这个目标。而 Miah 则需要再次循环结果。 - Toskan
glob
是更好的选择。 - Peter Krauss