如何以编程方式确定 PHP 中的文档根目录? [英] How to programmatically determine the document root in PHP?

查看:21
本文介绍了如何以编程方式确定 PHP 中的文档根目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我最近遇到的一个问题 - 网络主机上的 apache 配置错误.这意味着所有依赖 $_SERVER['DOCUMENT_ROOT'] 的脚本都会中断.我发现的最简单的解决方法是在一些共享的全局包含文件中设置变量,但不要忘记它是一种痛苦.我的问题是,如何以编程方式确定正确的文档根目录?

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'

真正的文档根是:

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

我想要一个从 www.example.com/blog/ 运行的脚本(在路径 /data/htdocs/example.com/www/blog>) 获取/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

有什么解决办法吗?或者是不依赖 $_SERVER['DOCUMENT_ROOT'] 并修复我在我的网站上运行的所有软件的唯一方法?在主机端修复此问题似乎不是一个选项,我还没有遇到过正确配置的主机.我得到的最好的是一个指向 www.example.com 的文档根目录,它至少在 open_basedir 内部——他们使用了另一种命名方案,www.example.com 将指向 /u2/www/example_com/data/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/.

推荐答案

基于 http://www.helicron.net/php/:

$localpath=getenv("SCRIPT_NAME");
$absolutepath=getenv("SCRIPT_FILENAME");
$_SERVER['DOCUMENT_ROOT']=substr($absolutepath,0,strpos($absolutepath,$localpath));     

我不得不更改 basename/realpath 技巧,因为它在我的主机上返回了一个空字符串.相反,我使用 SCRIPT_FILENAME.这可能不再适用于 IIS(但使用 $_SERVER 变量的原始脚本可能也不会).

I had to change the basename/realpath trick because it returned an empty string on my host. Instead, I use SCRIPT_FILENAME. This probably won't work on IIS anymore (but the original scripts that used the $_SERVER variable probably wouldn't either).

这篇关于如何以编程方式确定 PHP 中的文档根目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆