PHP Get Absolute Path, Document Root, Base URL
Get the absolute path
$base_dir = __DIR__;
Get the document root
$doc_root = $_SERVER['DOCUMENT_ROOT'];
$doc_root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']);
Get base URL of current script
// 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;