我正在尝试使用此代码读取和显示目录中的所有文件。 它适用于与脚本位于同一目录中的文件。但是,当我尝试在文件夹(文件/)中显示文件时,它给了我一些问题。
我尝试将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>";
?>
答案 0 :(得分:2)
您没有在数组中包含完整路径:
while($fname = readdir($dhandleFiles)) {
$files[] = 'files/' . $fname;
^^^^^^^^---must include actual path
}
请记住readdir()返回 ONLY 文件名,没有路径信息。
答案 1 :(得分:1)
如何使用glob函数。
<?php
define('MYBASEPATH' , 'files/');
foreach (glob(MYBASEPATH . '*.php') as $fname) {
if($fname != 'list.php' && $fname != 'error.php' && $fname != 'index.php') {
$files[] = $fname;
}
}
?>
答案 2 :(得分:1)
这应该有所帮助 - 请看一下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());
}
答案 3 :(得分:1)
这将从子目录中读取并打印文件名:
$d = dir("myfiles");
while (false !== ($entry = $d->read())) {
if ($entry != ".") {
if ($entry != "..") {
print"$entry";
}
}
}
$d->close();