PHP中区分文件和目录
我的问题是一个提取目录内容的 php 页面。
正如您在下面的代码片段中看到的,路径是通过 GET 传递的。
我第一次调用该页面时,可以正确读取所有内容,但如果您刚刚读取该文件夹包含子目录,则会将其识别为文件。
您有什么建议或解决方案吗?
谢谢
<?php
$path = $_GET['dir'];
function createDir($path) {
if ($handle = opendir($path)) {
echo "<ul>";
while (false !== ($file = readdir($handle))) {
if (is_dir($path . $file) && $file != '.' && $file != '..')
printSubDir($file, $path, $queue);
else if ($file != '.' && $file != '..')
$queue[] = $file;
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path) {
foreach ($queue as $file) {
printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li>";
// print a file
echo "</li>";
}
function printSubDir($dir, $path) {
echo "<li>";
// print a directory
echo "</li>";
}
createDir($path);
?>
my problem is a php page that extracts the contents of a directory.
As you can see in the snippet below, the path is passed via GET.
The first time I call the page reads everything correctly, but if you just read the folder contains a sub-directory, it is recognized as a file.
Do you have any advice or solution?
thanks
<?php
$path = $_GET['dir'];
function createDir($path) {
if ($handle = opendir($path)) {
echo "<ul>";
while (false !== ($file = readdir($handle))) {
if (is_dir($path . $file) && $file != '.' && $file != '..')
printSubDir($file, $path, $queue);
else if ($file != '.' && $file != '..')
$queue[] = $file;
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path) {
foreach ($queue as $file) {
printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li>";
// print a file
echo "</li>";
}
function printSubDir($dir, $path) {
echo "<li>";
// print a directory
echo "</li>";
}
createDir($path);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 DirectoryIterator 轻松实现此目的:
you could use the DirectoryIterator to easily achieve this:
您可以使用
is_dir()
或is_file()
来检查这一点,然后也使用递归函数来读取这些内容。如果只是将 is 标记为目录,则可以使用检查。http://php.net/manual/en/function.is-dir.php
You can use
is_dir()
oris_file()
to check this and than use recursive functions to read those as well. If it's just to mark is as a directory you can just use the check.http://php.net/manual/en/function.is-dir.php