I develop and deploy various PHP programs to various conditions. Especially on development conditions, they may be anywhere, from document_root to /Customers/me/Sites/ as well as /Customers/me/Sites/someapp/

Inside these programs I have to know in which the 'application root' is, once because the real path and when as URL. Path isn't any problem. Let us say I've got a bootstrap.php within the application root directory which does:

define("BASE_DIR", realpath(dirname(__FILE__)));

However, I've problems to dependably obtain the base URL. Of all conditions simply subtracting document root from BASE_DIR works:

define("BASE_URL", str_replace($_SERVER['DOCUMENT_ROOT'],'',BASE_DIR) . "/");

Now, my issue is: This doesn't focus on conditions where my application lies within my user directory because PHP still sees the primary document root. Has anybody solved this issue?

Anything including realpath() and DOCUMENT_ROOT will fail hard once the server's got aliases set up. Think about a scenario where Apache's got a configuration such as this:

DocumentRoot /home/httpd/html
Alias /testalias /home/otherdir

And also you access a script at example.com/testalias/script.php.

The script will return:

realpath(dirname(__FILE__)) -> /home/otherdir
$_SERVER['DOCUMENT_ROOT'] -> /home/httpd/html
BASE_DIR -> /home/otherdir
BASE_URL -> /home/otherdir/

but the relaxation from the site really is available in /home/httpd/html

You may have better luck rebuilding the URL according to $_SERVER['SCRIPT_NAME'], the path/script title area of the URL:

$_SERVER['SCRIPT_NAME'] -> /testalias/script.php