How to change DOCUMENT_ROOT for PHP

Posted: Fri, Apr 22 01:22 AM (PDT)

If you are running into issues with the $_SERVER["DOCUMENT_ROOT"] variable showing "/usr/local/data/www/"; when using PHP5 and need to have it point to your correct document root for your application, here is a simple tutorial for changing it.

Create a file document_root.php into your root application directory with follow the code:

<?
$_SERVER["DOCUMENT_ROOT"]  = "/vhosts/domain.com/"
?>

Add to your root application directory .htaccess with follow the code

php_value	auto_prepend_file	"/vhosts/domain.com/document_root.php"

This tells Apache to parse the document_root.php file before doing anything else.

If you have apache with dynamic virtual hosts, you can doing this automatically for each host

You just put the document_root_fix.php file to /usr/local/etc/ directory with follow the code:

<?
$document_root_fix = explode('.', $_SERVER["HTTP_HOST"]);
if ((count($document_root_fix) == 2) or (count($document_root_fix)  > 2)) {
        $_SERVER["DOCUMENT_ROOT"] = "/vhosts/".$document_root_fix[count($document_root_fix)-2].".".$document_root_fix[count($document_root_fix)-1]."/";
}
?>

And put into httpd.conf this line

php_value	auto_prepend_file	"/usr/local/etc/document_root_fix.php"

Finally we have ($_SERVER["DOCUMENT_ROOT"]):

domain.com = /vhosts/domain.com/
domain.us = /vhosts/domain.us/
yourdomain.net = /vhosts/yourdomain.net/

Tags: