PHP Get Absolute Path, Document Root, Base URL
Depending on your server configuration, getting correct path information can be challenging. For example, PHP does not provide a variable that will return the the base URL of your site. To help out, you can use the following code snippets to get the absolute path, document root, and base URL, respectively.
Get the absolute path
For example, if your script is included in /path/directory/
, the following code snippet will give you something like
.
/var/www/path/example.com/httpdocs/path/directory
$base_dir = __DIR__;
Note that the result does not include a trailing slash.
Get the document root
This returns the document root, without the script filename:
$doc_root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']);
For example, it will give you something like /var/www/path/example.com/httpdocs
.
Note that the result does not include a trailing slash.
Get base URL of current script
For example, if your script is included in the /path/directory/
of example.com
, the following code snippet will output http://example.com/path/directory
.
// base directory
$base_dir = __DIR__;
// server protocol
$protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
// domain name
$domain = $_SERVER['SERVER_NAME'];
// base url
$base_url = preg_replace("!^${doc_root}!", '', $base_dir);
// server port
$port = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
// put em all together to get the complete base URL
$url = "${protocol}://${domain}${disp_port}${base_url}";
echo $url; // = http://example.com/path/directory
Note that the result does not include a trailing slash.