这个问题在这里已经有了答案:Getting the names of all files in a directory with PHP (15 answers) PHP list all files in directory [duplicate] (5 answers) 9 年前关闭。
用 PHP 列出一个目录中的所有文件的最佳方法是什么?是否有 $_SERVER 函数可以执行此操作?我想列出 usernames/ 目录中的所有文件并使用链接遍历该结果,这样我只需单击文件名的超链接即可到达那里。谢谢!
$temp_files = glob(__dir__.'/*'); foreach($temp_files as $file) {.............}
您正在寻找命令 scandir。
$path = '/tmp';
$files = scandir($path);
以下代码将从 scandir
返回的数组中删除 .
和 ..
:
$files = array_diff(scandir($path), array('.', '..'));
检查一下: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;
glob()
! php.net/manual/en/function.glob.php
.html
个文件而没有包含 404
的文件,您可以使用您的解决方案在一个循环中执行此操作。 Miah,您必须再次遍历结果
不定期副业成功案例分享
$files
而是$filesAndDirs
$files = array_diff(scandir(__DIR__ .$path), array('.', '..'));
解决了这个问题。来自stackoverflow.com/questions/11885717/…array_values(array_diff(scandir($path), array('..', '.')));
之后使用 array_values() 重新索引数组