Skip to content

Instantly share code, notes, and snippets.

@dhavalv
Last active February 6, 2017 06:56
Show Gist options
  • Save dhavalv/bb222022beb3839ce90c0b9a6f50178d to your computer and use it in GitHub Desktop.
Save dhavalv/bb222022beb3839ce90c0b9a6f50178d to your computer and use it in GitHub Desktop.
PHP Document Root, Path and URL detection
Variable Content
base_dir /var/www/mywebsite
doc_root /var/www
base_url /mywebsite
protocol http
port 8080
domain example.com
full_url http://example.com:8080/mywebsite
$base_dir  = __DIR__; // Absolute path to your installation, ex: /var/www/mywebsite
$doc_root  = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']); # ex: /var/www
$base_url  = preg_replace("!^${doc_root}!", '', $base_dir); # ex: '' or '/mywebsite'
$protocol  = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$port      = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
$domain    = $_SERVER['SERVER_NAME'];
$full_url  = "${protocol}://${domain}${disp_port}${base_url}"; 
# Ex: 'http://example.com', 'https://example.com/mywebsite', etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment