PHP: How to get the document root from inside a user directory?

Stefan picture Stefan · Jan 8, 2011 · Viewed 14k times · Source

I develop and deploy various PHP applications to different environments. Especially on development environments, they can be anywhere, from document_root to /Users/me/Sites/ or even /Users/me/Sites/someapp/

Inside these applications I need to know where the 'application root' is, once as the real path and once as URL. Path is no problem. Let's say I have a bootstrap.php in the app root directory which does:

define("BASE_DIR", realpath(dirname(__FILE__)));

However, I have problems to reliably get the base URL. On most environments simply subtracting document root from BASE_DIR works:

define("BASE_URL", str_replace($_SERVER['DOCUMENT_ROOT'],'',BASE_DIR) . "/");

Now, my problem is: This does not work on environments where my app lies inside my user directory because PHP still sees the main document root. Has anyone solved this problem?

Answer

Marc B picture Marc B · Jan 8, 2011

Anything involving realpath() and DOCUMENT_ROOT is going to fail hard when the server's got aliases configured. Consider a scenario where Apache's got a configuration like this:

DocumentRoot /home/httpd/html
Alias /testalias /home/otherdir

And you access a script at example.com/testalias/script.php.

The script will return:

realpath(dirname(__FILE__)) -> /home/otherdir
$_SERVER['DOCUMENT_ROOT'] -> /home/httpd/html
BASE_DIR -> /home/otherdir
BASE_URL -> /home/otherdir/

and yet the rest of the site actually exists in /home/httpd/html

You might have better luck reconstructing the URL based on $_SERVER['SCRIPT_NAME'], which is the path/script name portion of the URL:

$_SERVER['SCRIPT_NAME'] -> /testalias/script.php