如何在php中循环父目录?

如何在php中循环父目录?

问题描述:

There are all these resources for recursively looping through sub directories, but I haven't found ONE that shows how to do the opposite.

This is what I want to do...

<?php

// get the current working directory

// start a loop

    // check if a certain file exists in the current directory

    // if not, set current directory as parent directory

// end loop

So, in other words, I'm searching for a VERY specific file in the current directory, if it doesn't exist there, check it's parent, then it's parent, etc.

Everything I've tried just feels ugly to me. Hopefully someone has an elegant solution to this.

Thanks!

所有这些资源都可以递归循环遍历子目录,但我还没有找到一个显示如何做的资源 相反。 p>

这就是我想要做的...... p>

 &lt;?php 
 
 //获取 当前工作目录
 
 //开始循环
 
 //检查当前目录中是否存在某个文件
 
如果没有,请将当前目录设置为父目录
 
 //结束 loop 
  code>  pre> 
 
 

因此,换句话说,我正在当前目录中搜索一个非常特定的文件,如果它不存在,请检查它的父文件, 那么它是父母等等。 p>

我尝试的一切都让我觉得难看。 希望有人有一个优雅的解决方案。 p>

谢谢! p> div>

Try to create a recursive function like this

function getSomeFile($path) {
    if(file_exists($path) {
        return file_get_contents($path);
    }
    else {
        return getSomeFile("../" . $path);
    }
}

The easiest way to do this would be using ../ this will move you to the folder above. You can then get a file/folder list for that directory. Don't forget that if you check children of the directory above you then you're checking your siblings. If you just want to go straight up the tree then you can simply keep stepping up a directory until you hit root or as far as you are permitted to go.

<?php

$dir = '.';
while ($dir != '/'){
    if (file_exists($dir.'/'. $filename)) {
        echo 'found it!';
        break;
    } else {
        echo 'Changing directory' . "
";
        $dir = chdir('..');
    }
}
?>

Modified mavili 's code:

function findParentDirWithFile( $file = false ) {
    if ( empty($file) ) { return false; }

    $dir = '.';

    while ($dir != '/') {
        if (file_exists($dir.'/'. $file)) {
            echo 'found it!';
            return $dir . '/' . $file;
            break;
        } else {
            echo 'Changing directory' . "
";
            chdir('..');
            $dir = getcwd();
        }
    }

}