可能是一个微不足道的问题,但我正在寻找一种方法来说明获取网站网址的根,例如:http://localhost/some/folder/containing/something/here/or/there
应该返回http://localhost/
我知道有,$_SERVER['DOCUMENT_ROOT']
但那不是我想要的.
我确信这很容易,但我一直在阅读:这篇文章试图找出我应该使用或调用的内容.
想法?
我所遇到的另一个问题是 - 这将是答案是什么,在网站上工作,http://subsite.localhost/some/folder/containing/something/here/or/there
所以我的最终结果是http://subsite.localhost/
boe*_*bot 46
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
Run Code Online (Sandbox Code Playgroud)
如果您对当前脚本的方案和主机感兴趣.
否则,就像已经建议的那样,是parse_url().例如
$parsedUrl = parse_url('http://localhost/some/folder/containing/something/here/or/there');
$root = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/';
Run Code Online (Sandbox Code Playgroud)
如果您还对路径之前的其他URL组件(例如凭据)感兴趣,您还可以在完整URL上使用strstr(),并将"path"作为指针,例如
$url = 'http://user:pass@localhost:80/some/folder/containing/something/here/or/there';
$parsedUrl = parse_url($url);
$root = strstr($url, $parsedUrl['path'], true) . '/';//gives 'http://user:pass@localhost:80/'
Run Code Online (Sandbox Code Playgroud)
dan*_*l__ 11
另一个简单方法:
<?php
$hostname = getenv('HTTP_HOST');
echo $hostname;
Run Code Online (Sandbox Code Playgroud)
(PHP 4,PHP 5)
getenv - 获取环境变量的值
此PHP函数返回完整路径的真实URL.
function pathUrl($dir = __DIR__){
$root = "";
$dir = str_replace('\\', '/', realpath($dir));
//HTTPS or HTTP
$root .= !empty($_SERVER['HTTPS']) ? 'https' : 'http';
//HOST
$root .= '://' . $_SERVER['HTTP_HOST'];
//ALIAS
if(!empty($_SERVER['CONTEXT_PREFIX'])) {
$root .= $_SERVER['CONTEXT_PREFIX'];
$root .= substr($dir, strlen($_SERVER[ 'CONTEXT_DOCUMENT_ROOT' ]));
} else {
$root .= substr($dir, strlen($_SERVER[ 'DOCUMENT_ROOT' ]));
}
$root .= '/';
return $root;
}
Run Code Online (Sandbox Code Playgroud)
在此文件中调用pathUrl:http://example.com/shop/index.php
#index.php
echo pathUrl();
//http://example.com/shop/
Run Code Online (Sandbox Code Playgroud)
使用别名:http://example.com/alias-name/shop/index.php
#index.php
echo pathUrl();
//http://example.com/alias-name/shop/
Run Code Online (Sandbox Code Playgroud)
对于子目录:http://example.com/alias-name/shop/inc/config.php
#config.php
echo pathUrl(__DIR__ . '/../');
//http://example.com/alias-name/shop/
Run Code Online (Sandbox Code Playgroud)