Find document root using FILE magic constant instead of using $ SERVER of DOCUMENT ROOT
From Code Trash
When a script is executed by a cron job $_SERVER array will be different comparing to normal request like http://sitename.com.
This is because the cron job runs the script from the shell (command line) like php /home/user/folder/filename.php at this time $_SERVER keys are different and will not have the DOCUMENT_ROOT key instead it has the following
[SHELL] => /bin/sh
[USER] => domainuser
[PATH] => /usr/bin:/bin
[PWD] => /home/domainuser
[SHLVL] => 1
[HOME] => /home/domainuser
[LOGNAME] => domainuser
[_] => /usr/bin/php
[PHP_SELF] =>
[REQUEST_TIME] => 1274434141
[argv] => Array
(
[0] => /home/domainuser/public_html/cronscriptname.php
)
You can see the difference in the $_SERVER array when it is executed as webapp.
Some times we need to read files form the disk to sent them as attacment or for any other purpose. We the document root.
to find the document root we can follow the following. it will work both when the scripts are executed as command line form the shell or as a webpage.
<? $file = __FILE__; if($_SERVER['SERVER_NAME']=='localhost') $root = str_replace('config\config.php','',$file); else $root = str_replace('config/config.php','',$file); //echo $root; ?>
Remove the relative path of any script in which you want to find the root so that you can extract the document root alone. just play it with a few examples and then you can get the whole picture if you are not able to get this.
and now the content of the variable of $root will be same when run either from the shell or by a client.
If you have any objection or thoughts then please post it to me.
