简体   繁体   English

动态获取网站根URL /基本URL

[英]Get the website root URL / base URL dynamically

Dn't know if this is at all possible - but let me explain my problem. 不知道这是否完全可能-但让我解释一下我的问题。

I'm working on a project with multiple developers. 我正在与多个开发人员进行项目。 We all have our own development environment set up. 我们都有自己的开发环境。 For some - the website we're building is located in one or more subfolders of their document root - for example 对于某些人-我们正在构建的网站位于其文档根目录的一个或多个子文件夹中-例如

/library/webserver/htdocs/project/website

Others have a different path the the site, like 其他人有不同的网站路径,例如

/htdocs/website

When it comes to finding a common way to get the document root (to include php files and such) it no problem. 当涉及到获取文档根目录的通用方法(包括php文件等)时,这没有问题。 But I'd like to also find the website root URL, meaning in the first case: 但我也想找到网站的根URL,在第一种情况下是这样:

http://localhost/project/website/

and in the second case 在第二种情况下

http://localhost/website/

In production, the same method should return simply 在生产中,相同的方法应该简单地返回

http://domain.tld.

Is there a nice way to do this - without having to define paths manually? 有没有一种不错的方法-不必手动定义路径? Thank you! 谢谢!

I ended up with a function looking like this. 我最终得到了一个看起来像这样的函数。 It uses the document root for the current server, but then strips away the part before directory name of the website root - which is really the directory name of the directory name one step above were this function is located: 它使用当前服务器的文档根目录,但是在网站根目录的目录名称之前剥去了一部分-这实际上是目录名称的目录名称,位于此功能的上方一步:

$dirName = dirname(dirname(__FILE__) . ".." . DIRECTORY_SEPARATOR);
$dirName = str_replace('\\', "/", $dirName);    
$base = str_replace($_SERVER['DOCUMENT_ROOT'], "", $dirName);

With a document root of /etc/webserver/documents/ and a website under /projects/website1 in your document root it would return /projects/website1 if this script is located in /projects/website1/somreDir/someFile.php . 如果文档脚本位于/projects/website1则文档根目录为/etc/webserver/documents/并且文档根目录中的/projects/website1下的网站将返回/projects/website1 /projects/website1/somreDir/someFile.php

Hopes this helps someone. 希望这对某人有帮助。

I think you're looking for $_SERVER['HTTP_ROOT'] : 我认为您正在寻找$_SERVER['HTTP_ROOT']

'HTTP_HOST' 'HTTP_HOST'

Contents of the Host: header from the current request, if there is one. 主机的内容:当前请求中的标头(如果有)。

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

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