John
John

Reputation: 3916

How to loop through parent directories in 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!

Upvotes: 1

Views: 353

Answers (4)

user1973303
user1973303

Reputation: 1

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' . "\n";
            chdir('..');
            $dir = getcwd();
        }
    }

}

Upvotes: 0

mavili
mavili

Reputation: 3424

<?php

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

Upvotes: 1

Scott Helme
Scott Helme

Reputation: 4799

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.

Upvotes: 1

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

Try to create a recursive function like this

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

Upvotes: 1

Related Questions