Sometimes $_SERVER['DOCUMENT_ROOT']
returns with a trailing slash. In other environments it does not. Where can this be specified?
You can not say in advance if $_SERVER['DOCUMENT_ROOT']
contains a slash at the end or not.
Normally, if properly configured, it does not contain a trailing slash. On Ubuntu (as well as on other UNIX), a properly written path to a directory does not have the /
at the end. On windows for example, apache will even refuse to start if it's configured with one. On UNIX Apache is not that picky and allows with a trailing slash.
But there is one exception, if you make your root directory (/
) your document root. Because of that case, you can not say in advance whether or not it contains a trailing slash.
In any case it contains the value of the DocumentRoot
directive - with or without trailing slash like it has been written into the httpd configuration file. PHP only takes over the value from apache. To get the real document root, use realpath
and/or conditionally add a slash (or remove it) at the end if either in your configuration file or within your PHP code.
I tend to use the current directory more than I use docroot because it also works well on command line and in unit tests too. I tend to use something like:
require_once(dirname(__FILE__).'/../../../../constants.php');
Rather than:
require_once($_SERVER['DOCUMENT_ROOT'].'/../constants.php');
I saw it first in Wordpress source and quite liked it, but it can lead to a lot of '../' repetition.
P.S. FILE is the current file and dirname will strip off the /something.php from the end therefore leaving the path of the directory containing the current file.
You can do like this, in order to make sure the trailing slash is always present
'/'.trim( $_SERVER['DOCUMENT_ROOT'], '/' ).'/'
require_once( '/'.trim( $_SERVER['DOCUMENT_ROOT'], '/' ).'/'.'constants.php' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With