PHP:如何从用户目录中获取文档根目录?
我开发各种 PHP 应用程序并将其部署到不同的环境。特别是在开发环境中,它们可以位于任何地方,从 document_root 到 /Users/me/Sites/ 甚至 /Users/me/Sites/someapp/
在这些应用程序中,我需要知道“应用程序根”在哪里,一旦作为真正的根路径和一次作为 URL。路径没有问题。假设我的应用程序根目录中有一个 bootstrap.php ,它的作用是:
define("BASE_DIR", realpath(dirname(__FILE__)));
但是,我在可靠地获取基本 URL 方面遇到了问题。在大多数环境中,只需从 BASE_DIR 中减去文档根即可:
define("BASE_URL", str_replace($_SERVER['DOCUMENT_ROOT'],'',BASE_DIR) . "/");
现在,我的问题是:这在我的应用程序位于用户目录内的环境中不起作用,因为 PHP 仍然会看到主文档根。有人解决这个问题了吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当服务器配置了别名时,任何涉及 realpath() 和 DOCUMENT_ROOT 的操作都会严重失败。考虑一个场景,其中 Apache 的配置如下:
您访问
example.com/testalias/script.php
上的脚本。脚本将返回:
但网站的其余部分实际上存在于
/home/httpd/html
中您可能会更好地基于
$_SERVER['SCRIPT_NAME']
重建 URL code>,这是 URL 的路径/脚本名称部分: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:
And you access a script at
example.com/testalias/script.php
.The script will return:
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: