从目录中读取文件名


Read file names from directory

我正在尝试使用此代码读取和显示目录中的所有文件。它适用于与脚本位于同一目录中的文件。但是当我尝试在文件夹(文件/)中显示文件时,它给我带来了问题。

我尝试将 directoy 变量设置为许多不同的东西。 像...
文件/
文件
/文件/
等。。。似乎什么都不起作用。有人知道为什么吗?

<?php
$dhandleFiles = opendir('files/');
$files = array();
if ($dhandleFiles) {
    while (false !== ($fname = readdir($dhandleFiles))) {
        if (is_file($fname) && ($fname != 'list.php') && ($fname != 'error.php') && ($fname != 'index.php')) {
            $files[] = (is_dir("./$fname")) ? "{$fname}" : $fname;
        }
    }
    closedir($dhandleFiles);
}
echo "Files";
echo "<ul>";
foreach ($files as $fname) {
    echo "<li><a href='{$fname}'>{$fname}</a></li>";
}
echo "</ul>";
?>

您没有在数组中包含完整路径:

while($fname = readdir($dhandleFiles)) {
    $files[] = 'files/' . $fname;
               ^^^^^^^^---must include actual path
}

请记住,readdir() 返回文件名,不返回路径信息。

这应该会有所帮助 - 也看看SplFileInfo。

<?php
class ExcludedFilesFilter extends FilterIterator {
    protected
        $excluded = array(
            'list.php',
            'error.php',
            'index.php',
        );
    public function accept() {
        $isFile     = $this->current()->isFile();
        $isExcluded = in_array($this->current(), $this->excluded);
        return $isFile && ! $isExcluded;
    }
}
$dir = new DirectoryIterator(realpath('.'));
foreach (new ExcludedFilesFilter($dir) as $file) {
    printf("%s'n", $file->getRealpath());
}

如何使用 glob 函数。

<?php
define('MYBASEPATH' , 'files/');
foreach (glob(MYBASEPATH . '*.php') as $fname) {
    if($fname != 'list.php' && $fname != 'error.php' && $fname != 'index.php') {
        $files[] = $fname;
    }
}
?>

在此处阅读有关获取目录中所有文件的更多信息

这会从子目录中读取和打印文件名:

$d = dir("myfiles");
while (false !== ($entry = $d->read())) {
  if ($entry != ".") {
    if ($entry != "..") {
        print"$entry";       
    }
  }
}
$d->close();