I have always had trouble reliably and dynamically finding what my application root was in PHP. There seemed no way to effectively determine what the application root was on the fly. I always keep my application root separate from my www root for security considerations. This knocks out using $_SERVER['DOCUMENT_ROOT'].
Consider the following directory structure:
/path/to/domain.com
--> app/
--> includes/main.php
--> www/
--> index.php
--> admin/index.phpSo the www/index.php file needs to include the app/includes/main.php file as follows:
require('../app/includes/main.php');And the www/admin/index.php file includes app/includes/main.php by:
require('../../app/includes/main.php');When app/includes/main.php is loaded by the referencing index.php pages it has no idea where it is located on the file system. Trying to figure out an absolute path to the application root by using $_SERVER['DOCUMENT_ROOT'] had always proven to have a hole of some description. Up to now I had not found a 100% effective way to determine the application root in PHP.
There is a PHP constant that allows for the determination of the application root and it is 100& effective. Welcome to the PHP constant __FILE__. When a file is included the __FILE__ constant has the absolute path to the included file and NOT the calling file. So when www/index.php and www/admin/index.php include the app/includes/index.php file __FILE__ is set to /path/to/domain/includes/main.php in both cases.
With a little bit of tweaking I can now reliably determine the application root:
define('APPLICATION_ROOT', realpath(dirname(__FILE__).'/../../').'/');The APPLICATION_ROOT constant will be populated with /path/to/domain/ allowing for absolute reference to any files in the app/ and www/ directories.
Now I can include files from any directory level using a standardized, dynamic (I can move the application root anywhere), and 100% effective method to determine the application root in PHP:
require(APPLICATION_ROOT.''app/includes/constants.php');
Comments
Post new comment