Search code examples
phprelative-pathdir

Why many PHP developers use "__DIR__ . '../otherFolder'"?


Often I see this type of code __DIR__.'/../Resources/config'. But why is the point, am I wrong that is it the same that typing ../Resources/config' ?


Solution

  • No, it's not always the same thing. __DIR__ is the directory of the file, not the current working directory. This code is essentially a dynamically-generated absolute path.

    Write this into ~/foo/script.php:

    <?php
    // Ta, Sven
    //  https://php.net/manual/en/function.realpath.php#84012
    function get_absolute_path($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return '/' . implode(DIRECTORY_SEPARATOR, $absolutes);
    }
    
    $p = __DIR__ . '/../bar';
    echo $p . "\n" . get_absolute_path($p) . "\n";
    ?>
    

    Now:

    $ cd ~/foo
    $ php script.php
    /home/me/foo/../bar
    /home/me/bar
    
    $ cd ~/
    $ php foo/script.php
    /home/me/foo/../bar
    /home/me/bar
    

    But if we got rid of __DIR__:

    $ cd ~/foo
    $ php script.php
    ../bar
    /home/me/bar
    
    $ cd ~/
    $ php foo/script.php
    ../bar
    /home/bar
    

    See ... that last path is incorrect.

    If we were using these paths anywhere, they'd be broken without __DIR__.

    Whenever you write a script, you should ensure that it is safe to execute it from some directory other than the one in which it lives!