PHP:如何从用户目录中获取文档根目录?

发布于 2024-10-11 04:32:08 字数 527 浏览 6 评论 0原文

我开发各种 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山人契 2024-10-18 04:32:08

当服务器配置了别名时,任何涉及 realpath() 和 DOCUMENT_ROOT 的操作都会严重失败。考虑一个场景,其中 Apache 的配置如下:

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

您访问 example.com/testalias/script.php 上的脚本。

脚本将返回:

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

但网站的其余部分实际上存在于 /home/httpd/html

您可能会更好地基于 $_SERVER['SCRIPT_NAME'] 重建 URL code>,这是 URL 的路径/脚本名称部分:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文