tags:

views:

104

answers:

3

Hey all,

I was wondering if there is some variable that will return what $_SERVER['DOCUMENT_ROOT'] returns when I call PHP like this: ./somescript

If not, how do people get around this case? I'm looking to be able to call the same script (a template compiler) in both the web browser and the terminal.

Thanks! Matt Mueller

A: 

hardcode document root in it.
hardcode is always a solution

Col. Shrapnel
Unfortunately that's not really an option because I'm looking to distribute the code.
Matt
@Matt omg distribute. make an installation script then, which will determine a document root and hardcode it for you. you can always use relative paths too
Col. Shrapnel
Just add: *Some configuration is required.
erisco
Ha. I'd rather try and be slightly less lazy than the people who use it. Thanks though.
Matt
this is really not a good solution, what if you had to move script or switch to another server.
Benoit
@Benoit feel free to tell us a better one
Col. Shrapnel
+1  A: 

I think you should use getcwd function to obtain current directory (or just dirname(__FILE__) if your script is the top one). Then you only need to be sure to run the script from your DOCUMENT_ROOT. Something like this:

cd /var/www/
php ./scripts/top.php
Denis Malinovsky
Hmm. I tried this before, I'm pretty sure it didn't work because the cwd wasn't always the same. It seems like this might be my only option though. Thanks!
Matt
You just need to be sure you did `cd` into required dir before running the script.
Denis Malinovsky
the question is how to determine required dir
Col. Shrapnel
Obviously you need to do it anyway to locate a script.
Denis Malinovsky
it was a question you tried to answer. how to determine. not how to set. sometimes I don't understand the ways answers being accepted on so
Col. Shrapnel
+3  A: 

I don't recommend the getcwd() command for this because you cannot be sure of where cwd is pointing unless you've made a chdir before (which mean you already know which directory you're in). Working directory can be define in php config and vary between apache and CLI, and some php frameworks changes it on startup.

Use dirname(__FILE__) it always works wether you're in a apache or cli context (plus it works on windows and unix), and if you need to move inside your project files you can just use relative paths.

Benoit
dirname(__FILE__) is not a synonym for the DOCUMENT_ROOT. Go figure
Col. Shrapnel
did not wrote it, but assumed running from a front controller script you should get document root, and running from elsewhere in a project you can parse with relative path to get down to document root without creating hard dependency on server configuration
Benoit