Reputation: 379
I have an account on a shared server which is no longer maintained and isn't very well configured.
echo $_SERVER["SCRIPT_FILENAME"] = '/path/to/my/root/and/now/path/to/my/file/location.php'
but ...
echo $_SERVER["DOCUMENT_ROOT"] = '/var/www'
I needed to find the site root so I wrote my own method to do so. What I am wondering is if anyone sees a reason why this wouldn't work consistently before I put it into production?
Note: I know that it won't work with includes/requires, url-rewriting or with index.php or any other root extensions apache is configured to access silently.
Here's my method:
define('ROOT_PATH', str_replace(str_replace('/'.basename(__FILE__),'',
$_SERVER["SCRIPT_URL"]),'',dirname(__FILE__)));
require_once ROOT_PATH.'/and/now/path/to/my/file/location.php';
In essence, it removes the script name from the script url, then removes any directory names found after the root.
EDIT: My description above said 'after the root' but the str_replace did not care where in the string that the replacement took place. This could have broken it. Therefore I have revised my solution to only replace the last instance of the matching paths:
define('ROOT_PATH',preg_replace('(.*)'.
preg_quote(str_replace('/'.basename(__FILE__),'',
$_SERVER["SCRIPT_URL"]),'~').'(.*?)~','$1'.''.'$2',dirname(__FILE__),1));
preg_replace
is a little slower unfortunately.
Upvotes: 0
Views: 732
Reputation: 29985
The best approach would be to just avoid using that at all, and define an 'application root' instead. If your index.php
is in this file, you should just :
define('APP_ROOT', dirname(__FILE__));
If you want to define this in some included file instead, for example includes/approot.php
, just call dirname
again for every subfolder :
define('APP_ROOT', dirname(dirname(__FILE__)));
Knowing the document root isn't that useful. Knowing the application root is.
Upvotes: 2