从目录中读取文件名
问题描述:
我正尝试使用此代码读取并显示目录中的所有文件。 对于与脚本相同的目录中的文件,它工作正常。但是,当我尝试显示文件夹中的文件(文件/)时,它给我带来了问题。从目录中读取文件名
我试着将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>";
?>
答
这将有助于 - 看看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());
}
答
你不包括阵列中的完整路径:
while($fname = readdir($dhandleFiles)) {
$files[] = 'files/' . $fname;
^^^^^^^^---must include actual path
}
记住的readdir()返回ONLY文件名,不带路径信息。
答
如何使用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();
什么相对于这个脚本的目录结构是什么?与此脚本位于同一文件夹内的“files”目录是什么? – KHMKShore
正确,文件目录与脚本处于同一级别。 – Frantumn