WP-Mix

A fresh mix of code snippets and tutorials

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

If your script is included in /path/directory/, this code snippet:

$base_dir = __DIR__;

..returns something like this (depending on actual server path):

/var/www/path/example.com/httpdocs/path/directory

Note that the result does not include a trailing slash.

Get the document root

The easiest, cleanest way to get the document root:

$doc_root = $_SERVER['DOCUMENT_ROOT'];

..which returns something like:

/var/www/path/example.com/httpdocs

Note that the result does not include a trailing slash.

Alternately you can do this:

$doc_root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']);

The first way is preferred, the second way is for your information.

Get base URL of current script

This code snippet returns the base URL of the current script. So let’s say that our script is included inside of /path/directory/ at example.com. To get the base URL, apply the following code:

// 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;

That will output something like this:

http://example.com/path/directory

Note that the result does not include a trailing slash.

WP-Mix File-Path Trilogy

★ Pro Tip:

USP ProSAC Pro