function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
Run Code Online (Sandbox Code Playgroud)
例如,使用上面的函数,如果我使用相同的目录,它工作正常,但如果我创建一个子目录,并在其中工作,它也将给我子目录的位置,例如.我只是想要,example.com
但它给了我,example.com/sub
如果我在文件夹中工作sub
.如果我正在使用主目录,该功能正常.有替代品$_SERVER['HTTP_HOST']
吗?
或者我怎么能修复我的功能/代码才能获得主网址?谢谢.
Bad*_*olf 82
使用SERVER_NAME
.
echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
Run Code Online (Sandbox Code Playgroud)
小智 32
你可以使用PHP的parse_url()
功能
function url($url) {
$result = parse_url($url);
return $result['scheme']."://".$result['host'];
}
Run Code Online (Sandbox Code Playgroud)
bar*_*hin 23
最短的解决方案:
$domain = parse_url('http://google.com', PHP_URL_HOST);
Run Code Online (Sandbox Code Playgroud)
Jas*_*een 21
/**
* Suppose, you are browsing in your localhost
* http://localhost/myproject/index.php?id=8
*/
function getBaseUrl()
{
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
// return: http://localhost/myproject/
return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
}
Run Code Online (Sandbox Code Playgroud)
使用parse_url()
这样:
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
}
Run Code Online (Sandbox Code Playgroud)
这是另一个较短的选项:
function url(){
$pu = parse_url($_SERVER['REQUEST_URI']);
return $pu["scheme"] . "://" . $pu["host"];
}
Run Code Online (Sandbox Code Playgroud)
首先修剪 URL 中的尾部反斜杠 (/)。例如,如果 URL 是http://www.google.com/,那么结果 URL 将是http://www.google.com
$url= trim($url, '/');
Run Code Online (Sandbox Code Playgroud)
如果 URL 中未包含方案,则将其添加到前面。例如,如果 URL 是 www.google.com,那么结果 URL 将是http://www.google.com
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
Run Code Online (Sandbox Code Playgroud)
获取 URL 的部分。
$urlParts = parse_url($url);
Run Code Online (Sandbox Code Playgroud)
现在删除www。从网址
$domain = preg_replace('/^www\./', '', $urlParts['host']);
Run Code Online (Sandbox Code Playgroud)
没有 http 和 www 的最终域现在存储在 $domain 变量中。
例子:
http://www.google.com => google.com
https://www.google.com => google.com
www.google.com => google.com
http://google.com => google.com