简体   繁体   English

PHP在配置错误的共享服务器上定义文档根目录

[英]PHP defining document root on badly configured shared server

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. 注意:我知道它不能与includes / requires,url-rewriting或index.php或任何其他根扩展一起使用apache配置为静默访问。

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. 实质上,它从脚本URL中删除脚本名称,然后删除在根​​目录后找到的所有目录名称。

EDIT: My description above said 'after the root' but the str_replace did not care where in the string that the replacement took place. 编辑:我上面的描述'在root之后'但是str_replace并不关心替换发生在字符串中的哪个位置。 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. 不幸的是, preg_replace有点慢。

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 : 如果你的index.php在这个文件中,你应该只:

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 : 如果你想在一些包含的文件中定义它,例如includes/approot.php ,只需为每个子文件夹再次调用dirname

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

Knowing the document root isn't that useful. 了解文档根目录并不是很有用。 Knowing the application root is. 知道应用程序根目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM