PHP 目录列表代码故障

发布于 2024-07-26 15:12:13 字数 798 浏览 2 评论 0原文

我尝试编写一个脚本来列出目录和子目录等中的所有文件。如果我不包括检查是否有任何文件是目录,则该脚本可以正常工作。 该代码不会生成错误,但会生成一百行文本“Directory Listing of .”。 而不是我所期待的。 知道为什么这不起作用吗?

<?php

//define the path as relative
$path = "./";

function listagain($pth)
{
//using the opendir function
$dir_handle = @opendir($pth) or die("Unable to open $pth");

echo "Directory Listing of $pth<br/>";

//running the while loop
while ($file = readdir($dir_handle)) 
{
    //check whether file is directory
    if(is_dir($file))
    {
        //if it is, generate it's list of files
        listagain($file);
    }
    else
    {
        if($file!="." && $file!="..")
        echo "<a href='$file'>$file</a><br/>";
    }
}
//closing the directory
closedir($dir_handle);
}

listagain($path)

?> 

I tried to write a script to list all files in directories and subdirectories and so on.. The script works fine if I don't include the check to see whether any of the files are directories. The code doesn't generate errors but it generates a hundred lines of text saying "Directory Listing of ." instead of what I was expecting. Any idea why this isn't working?

<?php

//define the path as relative
$path = "./";

function listagain($pth)
{
//using the opendir function
$dir_handle = @opendir($pth) or die("Unable to open $pth");

echo "Directory Listing of $pth<br/>";

//running the while loop
while ($file = readdir($dir_handle)) 
{
    //check whether file is directory
    if(is_dir($file))
    {
        //if it is, generate it's list of files
        listagain($file);
    }
    else
    {
        if($file!="." && $file!="..")
        echo "<a href='$file'>$file</a><br/>";
    }
}
//closing the directory
closedir($dir_handle);
}

listagain($path)

?> 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残疾 2024-08-02 15:12:17

问题是,变量 $file 仅包含路径的基本名称。 因此,您需要使用$pth.$file

The problem is, variable $file contains only basename of path. So, you need to use $pth.$file.

GRAY°灰色天空 2024-08-02 15:12:16

第一个实体 ... 分别指当前目录和父目录。 所以你会得到无限递归。

在检查文件类型之前,您应该首先检查这一点:

if ($file!="." && $file!="..") {
    if (is_dir($file)) {
        listagain($file);
    } else {
        echo '<a href="'.htmlspecialchars($file).'">'.htmlspecialchars($file).'</a><br/>';
    }
}

The first enties . and .. refer to the current and parent directory respectivly. So you get a infinite recursion.

You should first check for that before checking the file type:

if ($file!="." && $file!="..") {
    if (is_dir($file)) {
        listagain($file);
    } else {
        echo '<a href="'.htmlspecialchars($file).'">'.htmlspecialchars($file).'</a><br/>';
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文