Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

apache - How to programmatically determine the document root in PHP?

Here's a problem that I've been running into lately - a misconfigured apache on a webhost. This means that all scripts that rely on $_SERVER['DOCUMENT_ROOT'] break. The easiest workaround that I've found is just set the variable in some global include files that is shared, but it's a pain not to forget it. My question is, how do I determine the correct document root programatically?

For example, on one host, the setup is like this:

$_SERVER['DOCUMENT_ROOT'] == '/htdocs'

The real document roots are:

test.example.com -> /data/htdocs/example.com/test
www.example.com -> /data/htdocs/example.com/www

And I'd like a script that's run from www.example.com/blog/ (on the path /data/htdocs/example.com/www/blog) to get the correct value of /data/htdocs/example.com/www.

On another host, the setup is a bit different:

$_SERVER['DOCUMENT_ROOT'] == '/srv'
test.example.com -> /home/virtual_web/example.com/public_html/test
www.example.com -> /home/virtual_web/example.com/public_html/www

Is there any solution to this? Or is the only way simply not to ever rely on $_SERVER['DOCUMENT_ROOT'] and fix all the software that I'm running on my sites? Fixing this on the hosting's side doesn't seem to be an option, I've yet to encounter a host where this is was configured correctly. The best I got was a document root pointing to www.example.com, which was at least inside open_basedir - they used yet another naming scheme, www.example.com would point to /u2/www/example_com/data/www/.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In PHP5 there is the magic constant __FILE__ that contains the absolute path of the file in which it appears. You can use it in combination with dirname to calculate the document root.

You can put a statement like the following one in a config file

define ('DOCUMENT_ROOT', dirname(__FILE__));

this should do the trick


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...