Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to find application root?

There is $_SERVER['DOCUMENT_ROOT'] that should have the root path to your web server.

Edit: If you look at most major php programs. When using the installer, you usually enter in the full path to the the application folder. The installer will just put that in a config file that is included in the entire application. One option is to use an auto prepend file to set the variable. another option is to just include_once() the config file on every page you need it. Last option I would suggest is to write you application using bootstrapping which is where you funnel all requests through one file (usually with url_rewrite). This allows you to easily set/include config variables in one spot and have them be available throughout all the scripts.


I usually store config.php file in ROOT directory, and in config.php I write:

define('ROOT_DIR', __DIR__);

And then just use ROOT_DIR constant in all other scripts. Using $_SERVER['DOCUMENT_ROOT'] is not very good because:

  • It's not always matching ROOT_DIR
  • This variable is not available in CGI mode (e.x. if you run your scripts by CRON)

It's nice to be able to use the same code at the top of every script and know that your page will load properly, even if you are in a subdirectory. I use this, which relies on you knowing what your root directory is called (typically, 'htdocs' or 'public_html':

defined('SITEROOT') or define('SITEROOT', substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos($_SERVER['DOCUMENT_ROOT'], 'public_html')) . 'public_html');

With SITEROOT defined consistently, you can then access a config file and/or page components without adapting paths on a script-by-script basis e.g. to a config file stored outside your root folder:

require_once SITEROOT . "/../config.php";