determining the application root path and url in php
by Gabi SolomonIf you buid any web application you will eventually need to find a way to specify the application root path and URL. This is inevitable if you don't build your links in a relative way ( by unsing ./ and ../ combinations ), and also if you want to have a way of keeping things organized and working even if you move script to a new server or in a folder.
Well there are several ways you can do this. The first one would be to write them in a config file by hand, and edit them as you move the project.
But even if that works well, it will give a bit of work when you move the application since you have to edit them by hand.
So the next method would be to have them be generated automatically. The ROOT_PATH is relatively easy to determine . What i do is have a directory called config in wich i place my config files, in it i have one called main_config.php which includes the rest of the config files. One of them is called paths.php.
Now to determine the root_path i use a function called dirname() and the __FILE__ constant.
Now we have the root_path solved and base_url to some extend, but need to specify the project directory.
We can solve that too automatically.
-
$projectDir = implode('/', array_intersect(explode('/', $_SERVER["REQUEST_URI"]), explode('/', str_replace('\\', '/', ROOT_PATH))));
-
$projectDir .= '/';
-
}
What that code does is take the ROOT_PATH that we defined and the REQUEST_URI from the server global variable and do an intersection of them to determine the project dir.
Hope this small snippet helped you.
Cheers
Related Posts
-
Gabi Solomon
-
URL Directory

