PHP how to find application root?

72,864

Solution 1

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.

Solution 2

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)

Solution 3

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";
Share:
72,864
Admin
Author by

Admin

Updated on August 14, 2020

Comments

  • Admin
    Admin over 3 years

    I'm having problems with my include files. I don't seem to be able to figure out how to construct my URLs when I use require_once('somefile.php'). If I try to use an include file in more than one place where the directory structures are different, I get an error that the include file cannot be found.

    In asp.net, to get my application root path, I can use ~/directory/file.aspx. The tild forward slash always knows that I am referencing from my website root and find the file no matter where the request comes from within my website. It always refers back to the root and looks for the file from there.

    QUESTION: How can I get the root path of my site? How can I do this so I can reuse my include files from anywhere within my site? Do I have to use absolute paths in my URLs?

    Thank you!