# Determine base URL of PHP app

I have this little piece of code which determines the base URL of PHP:

$root =$_SERVER["SERVER_NAME"];
if(basename(__FILE__) !== trim($_SERVER["PHP_SELF"], "/\\")) {$root .= "/" . basename(__DIR__);
}


This is working for me, but are there other solutions for this "problem," or are there any cases where this would fail?

• Can you provide an example of how this works? – pppp Sep 6 '16 at 8:54

$request = explode('/',$_SERVER['SCRIPT_NAME']);
array_pop($request); echo$_SERVER['SERVER_NAME'] . implode('/', $request);  It makes use of server's script name. Given the sample servername/one/two/index.php, it will return /one/two/index.php. We then remove the script from the directory using explode and popping the result, and then finally concatenating it to the server name. • Both the OP example and your example will cause a notice in a command line environment, where $_SERVER['SERVER_NAME'] is undefined. – Conor Mancone Sep 14 '17 at 19:12