就像,我们有文件夹/images/
,里面有一些文件。
脚本/scripts/listing.php
如何在/images/
中获取文件夹listing.php
内所有文件的名称?
感谢。
答案 0 :(得分:8)
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
/* This is the WRONG way to loop over the directory. */
while ($file = readdir($handle)) {
echo "$file\n";
}
closedir($handle);
}
?>
请参阅:readdir()
答案 1 :(得分:3)
答案 2 :(得分:2)
使用scandir
或dir
会使此问题变得微不足道。要获取索引从.
开始的数组中除特殊文件..
和0
之外的目录中的所有文件,可以将scandir
与array_diff
结合使用array_merge
:
$files = array_merge(array_diff(scandir($dir), Array('.','..')));
// $files now contains the filenames of every file in the directory $dir
答案 3 :(得分:2)
以下是使用SPL DirectoryIterator类的方法:
<?php
foreach (new DirectoryIterator('../images') as $fileInfo)
{
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
?>
答案 4 :(得分:1)
只是对Enrico的帖子进行了扩展,还需要进行一些检查/修改。
class Directory
{
private $path;
public function __construct($path)
{
$path = $path;
}
public function getFiles($recursive = false,$subpath = false)
{
$files = array();
$path = $subpath ? $subpath : $this->path;
if(false != ($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
if($recursive && is_dir($file) && $file != '.' && $file != '..')
{
array_merge($files,$this->getFiles(true,$file));
}else
{
$files[] = $path . $file;
}
}
}
return $files;
}
}
用法如下:
<?php
$directory = new Directory("/");
$Files = $directory->getFiles(true);
?>
这将为您提供如下列表:
/index.php
/includes/functions.php
/includes/.htaccess
//...
这有助于。