DGM DGM - 2 months ago 7x
PHP Question

How can I find an application's base url?

I'd like to find the base url of my application, so I can automatically reference other files in my application tree...

So given a file config.php in the base of my application, if a file in a subdirectory includes it, knows what to prefix a url with.


So given that
is accessed, I want it to be able to know that the css file is in
. In this case,
is "
" but I'd like it to know if the application is installed elsewhere.

I'm not sure if it's possible, many applications (phpMyAdmin, Squirrelmail I think) have to set a config variable to begin with. It would be more user friendly if it just knew.


I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it.

define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/');

$tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));
$tempPath2 = explode('/', substr(ABSPATH, 0, -1));
$tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));

for ($i = count($tempPath2); $i < count($tempPath1); $i++)
    array_pop ($tempPath3);

$urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);

if ($urladdr{strlen($urladdr) - 1}== '/')
    define('URLADDR', 'http://' . $urladdr);
    define('URLADDR', 'http://' . $urladdr . '/');

unset($tempPath1, $tempPath2, $tempPath3, $urladdr);

The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod_rewrite situations.