Spiga

determining the application root path and url in php

by Gabi Solomon

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

PHP:
  1. define('ROOT_PATH', '/home/user/public_html/folder/');
  2. define('PROJECT_DIR', '/folder/');
  3. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

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.

PHP:
  1. define('ROOT_PATH', dirname(dirname(__FILE__)));
  2. define('PROJECT_DIR', '/folder/');
  3. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

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.

PHP:
  1. define('ROOT_PATH', '/home/user/public_html/folder/');
  2. $projectDir = implode('/', array_intersect(explode('/', $_SERVER["REQUEST_URI"]), explode('/', str_replace('\\', '/', ROOT_PATH))));
  3. if ($projectDir[strlen($projectDir)-1] != '/') {
  4.         $projectDir .= '/';
  5. }
  6. define('PROJECT_DIR', $projectDir);
  7. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

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

blog comments powered by Disqus