Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' ?

like image 990
ricko zoe Avatar asked Oct 22 '15 17:10

ricko zoe


2 Answers

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!

like image 161
Lightness Races in Orbit Avatar answered Oct 20 '22 01:10

Lightness Races in Orbit


Because in many cases the relative path won't work, for example when the script is run from some other folder. Using __ DIR __ converts the relative path into absolute path, leaving no space for any confusion.

For your question lets suppose this hierarchy,

/
test/
test/script.php
test/Resource/config
another/

Now script.php contains this path, you run the script from the directory test so the relative path is resolved to test/Resource/config. Its what you wanted.

But if you run the script from say another, then the path will be resolved to another/Resource/config which is not right.

If you have used __DIR__, it always get resolved into the path of the script that it is used in. So the relative path would have become /test/Resource/config

Now no matter from where you run this script, since the path is absolute, it won't be resolved relatively and will remain the same.

like image 6
Akshendra Pratap Avatar answered Oct 20 '22 00:10

Akshendra Pratap