简体   繁体   English

您如何使用PHP在父目录级别列出目录?

[英]How do you use PHP to list the directories at the parent directory level?

I am trying to make a dynamic menu of the directories at the parent directory level using PHP. 我正在尝试使用PHP在父目录级别创建目录的动态菜单。 I can get the child directories with the following code: 我可以使用以下代码获取子目录:

<?php
    if ($handle = opendir('.')) 
    {
        while (false !== ($file = readdir($handle))) 
        {
            if ($file != "." && $file != "..") 
            {
                if(is_dir($file))
                {
                    echo '<a href="./' . $file . '">' . $file . '</a><br/>';
                }
            }
        }
        closedir($handle);
    }
?>

When I change opendir to ('..') or ('...') nothing seems to come back. 当我将opendir更改为('..')或('...')时,似乎什么也没回来。 I would like to do something like this: 我想做这样的事情:

 /
 |-A
 | |-1
 |-B
 | |-1
 | |-2
 | |-3
 |   |-a
 |   |-b
 |-C

Where if I were down in the /B/2 page, the php output would show that the parent directory level list would have links to A, B, and C and not something symbolic like '..'. 如果我在/ B / 2页中处于下降状态,则php输出将显示父目录级别列表将具有指向A,B和C的链接,而不是诸如“ ..”之类的符号。 The same code would show the same parent level directories if I were in /A/1. 如果我在/ A / 1中,则相同的代码将显示相同的父级目录。 If I were in /B/3/a the code would list 1, 2, and 3. Is this possible? 如果我在/ B / 3 / a中,则代码将列出1、2和3。这可能吗? If so how would I modify the code to accomplish this? 如果是这样,我将如何修改代码以实现此目的?

The filename argument to functions like is_dir() are interpreted relative to the process's current directory, which is not the same directory that you supplied to opendir() . is_dir()这样的函数的filename参数是相对于进程的当前目录解释的,该目录与您提供给opendir() You need to prepend the directory: 您需要在目录前添加:

if (is_dir("../$file")) {

You would need to link it like this: 您需要像这样链接它:

<a href="../A/1">A</a>
<a href="../B/1">A</a>
<a href="../C/1">A</a>

It turns out that is was a matter of testing to see if I had a line on a directory. 事实证明,这是测试是否在目录上有一行的问题。 Notice that the sequence begins with 请注意,该序列以

if (is_dir('../'))
{

}

The answer looks like this. 答案看起来像这样。

<?php
if (is_dir('../'))
{
  if ($dirhandle = opendir($dir))
  {
    while (($directory = readdir($dirhandle)) !== false)
    {
        if ($directory != "." && 
            $directory != ".." && 
            $directory != ".DS_Store" && 
            $directory != ".metadata"
            )
        {
            echo  '<a href="../' . $directory . '">'. $directory . '</a><br>' . "\n";    
        }
    }
    closedir($dh);
  }
}
?>

You can then modify the list of things your do not want to have listed eg index.php. 然后,您可以修改的东西你希望有上市如index.php文件列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM