PHP: How to get the document root from inside a user directory?

拥有回忆 提交于 2019-12-06 12:29:18

问题


I develop and deploy various PHP applications to different environments. Especially on development environments, they can be anywhere, from document_root to /Users/me/Sites/ or even /Users/me/Sites/someapp/

Inside these applications I need to know where the 'application root' is, once as the real path and once as URL. Path is no problem. Let's say I have a bootstrap.php in the app root directory which does:

define("BASE_DIR", realpath(dirname(__FILE__)));

However, I have problems to reliably get the base URL. On most environments simply subtracting document root from BASE_DIR works:

define("BASE_URL", str_replace($_SERVER['DOCUMENT_ROOT'],'',BASE_DIR) . "/");

Now, my problem is: This does not work on environments where my app lies inside my user directory because PHP still sees the main document root. Has anyone solved this problem?


回答1:


Anything involving realpath() and DOCUMENT_ROOT is going to fail hard when the server's got aliases configured. Consider a scenario where Apache's got a configuration like this:

DocumentRoot /home/httpd/html
Alias /testalias /home/otherdir

And you access a script at example.com/testalias/script.php.

The script will return:

realpath(dirname(__FILE__)) -> /home/otherdir
$_SERVER['DOCUMENT_ROOT'] -> /home/httpd/html
BASE_DIR -> /home/otherdir
BASE_URL -> /home/otherdir/

and yet the rest of the site actually exists in /home/httpd/html

You might have better luck reconstructing the URL based on $_SERVER['SCRIPT_NAME'], which is the path/script name portion of the URL:

$_SERVER['SCRIPT_NAME'] -> /testalias/script.php


来源:https://stackoverflow.com/questions/4634869/php-how-to-get-the-document-root-from-inside-a-user-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!