Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__DIR__ and DOCUMENT_ROOT return different values, but both work. Why?

Tags:

php

I have saved this code as dr.php in the root of a client's host. As could be seen in the output, __DIR__ is different from $_SERVER['DOCUMENT_ROOT']; but they both find the dr.php.

What is going on? Is it safe to assume DOCUMENT_ROOT always works?

Code of dr.php

<pre>
<?php
var_dump($_SERVER['DOCUMENT_ROOT']);
var_dump(file_exists($_SERVER['DOCUMENT_ROOT'] . '/dr.php'));
var_dump(__DIR__);
var_dump(file_exists(__DIR__ . '/dr.php'));
?>
</pre>

The output

string(36) "/usr/local/etc/httpd/htdocs/daikaidk"
bool(true)
string(34) "/usr/local/apache2/htdocs/daikaidk"
bool(true)
like image 297
Majid Fouladpour Avatar asked Jul 22 '26 01:07

Majid Fouladpour


1 Answers

According to the doc

__DIR__ : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.

and

__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.

So, you have configured your web server (Apache) with DOCUMENT ROOT /usr/local/etc/httpd/htdocs/daikaidk that's a symbolic link to /usr/local/apache2/htdocs/daikaidk.

In PHP __DIR__ returns the real path with symlinks resolved.

like image 188
Luca Rainone Avatar answered Jul 24 '26 18:07

Luca Rainone