Determine base URL of PHP app
Your code will work for one level deep working directories such as:


servername/admin/index.php
servername/sample/test.php


However, go one level deeper and it will not work. If I have servername/one/two/index.php, I will get a servername/two. It is because the basename() returns the working folder of the file.

I find this code useful for common applications:

$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.