在 PHP 中获取 webroot

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2424606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:25:01  来源:igfitidea点击:

Get webroot in PHP

php

提问by Aadi

I am using Apache server for PHP. How can I retrieve my web root in PHP, like http://localhost/testthesis/?

我正在为PHP使用 Apache 服务器。如何在 PHP 中检索我的 Web 根目录,例如http://localhost/testthesis/

回答by Phil Rykoff

Relative paths

相对路径

For your webservers root directory, use:

对于您的网络服务器根目录,请使用:

$folder = '/';

For the directory of the retrieved script, use:

对于检索到的脚本的目录,使用:

$folder = './';

Absolute paths (from the client's perspective)

绝对路径(从客户的角度)

For your webservers root directory, use:

对于您的网络服务器根目录,请使用:

$protocol = $_SERVER['HTTPS'] == '' ? 'http://' : 'https://';
$folder = $protocol . $_SERVER['HTTP_HOST'];

For the directory of the retrieved script, use:

对于检索到的脚本的目录,使用:

$protocol = $_SERVER['HTTPS'] == '' ? 'http://' : 'https://';
$folder = $protocol . $_SERVER['HTTP_HOST'] . '/' . basename($_SERVER['REQUEST_URI']);

回答by abbotto

Here is one way of doing it:

这是一种方法:

$web_root = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";

OUTPUT -->http://website.com/parent_folder/

回答by Your Common Sense

Web root is alwaysjust /. You'd never need the hostname or protocol part, and root can be only root of the server, not some folder or file.

Web 根始终只是/. 您永远不需要主机名或协议部分,root 只能是服务器的根,而不是某个文件夹或文件。

If you need some path, like /testthesis/- there are ways, but it has nothing common with web root.

如果你需要一些路径,比如/testthesis/- 有很多方法,但它与 web root没有什么共同之处。

If you need a filesystem directory for the webroot - it's in the $_SERVER['DOCUMENT_ROOT']variable.

如果您需要 webroot 的文件系统目录 - 它在$_SERVER['DOCUMENT_ROOT']变量中。

回答by jwhat

What you're looking for is not a webroot but rather a URL.

您要查找的不是 webroot 而是 URL。

You can get your current URL like so:

您可以像这样获取当前的 URL:

$protocol = strpos($_SERVER['SERVER_SIGNATURE'], '443') !== false ? 'https://' : 'http://';
$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];