【发布时间】:2011-05-11 03:06:24
【问题描述】:
比如,我们有文件夹/images/,里面有一些文件。
还有脚本/scripts/listing.php
我们如何获取文件夹/images/、listing.php 中所有文件的名称?
谢谢。
【问题讨论】:
比如,我们有文件夹/images/,里面有一些文件。
还有脚本/scripts/listing.php
我们如何获取文件夹/images/、listing.php 中所有文件的名称?
谢谢。
【问题讨论】:
<?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);
}
?>
【讨论】:
【讨论】:
这是一个使用 SPL DirectoryIterator 类的方法:
<?php
foreach (new DirectoryIterator('../images') as $fileInfo)
{
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
?>
【讨论】:
只是扩展 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
//...
希望这会有所帮助。
【讨论】: