如何使用PHP获取基本URL?

161
我正在使用 Windows Vista 上的 XAMPP。在我的开发中,我有 http://127.0.0.1/test_website/
如何用 PHP 获得 http://127.0.0.1/test_website/
我尝试了一些类似这样的方法,但都没有成功。
echo dirname(__FILE__)
or
echo basename(__FILE__);
etc.

1
它们为什么不起作用?它们返回了什么? - animuson
6
@animuson这些常量返回本地文件系统路径,而不是URL。 - ceejayoz
可能是获取PHP中完整的URL的重复问题。 - T.Todua
25个回答

286

试试这个:

<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>

了解有关$_SERVER 预定义变量的更多信息。

如果您计划使用 https,可以使用此代码:

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

echo url();
#=> http://127.0.0.1/foo

根据这个回答,请确保正确配置您的Apache,以便可以安全地依赖SERVER_NAME

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost>

注意: 如果您依赖于包含用户输入的HTTP_HOST键,则仍需要进行一些清理,删除空格、逗号、回车等任何不是域的有效字符。请查看PHP内置的parse_url函数进行示例。


2
应该检查 $_SERVER['HTTPS'] 并在这些情况下替换为 https:// 而不是 http:// - ceejayoz
2
感谢您,我需要这个函数。 - Brice Favre
2
$_SERVER['REQUEST_SCHEME']怎么样?这不是更简单吗? - frostymarvelous
3
如果您使用的端口不是80,这将无法正常工作。:( - M'sieur Toph'
1
@admdrew 谢谢。我双重检查了REQUEST_URI已经包含/;它确实包含。@swarnendu 在编辑他人答案时请更加小心,那应该是一条评论。 - maček
显示剩余11条评论

32

函数已调整以避免警告:

function url(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

23

有趣的“base_url”代码片段!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
}

使用方法简单:

//  url like: https://dev59.com/v3E85IYBdhLWcg3wXCEv

echo base_url();    //  will produce something like: https://dev59.com/v3E85IYBdhLWcg3wXCEv
echo base_url(TRUE);    //  will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE);    //  will produce something like: http://stackoverflow.com/questions/
//  and finally
echo base_url(NULL, NULL, TRUE);
//  will produce something like: 
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/2820723/"
//      }

17
   $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';

使用方法:

print "<script src='{$base_url}js/jquery.min.js'/>";

15
$modifyUrl = parse_url($url);
print_r($modifyUrl)

它很容易使用
输出:

Array
(
    [scheme] => http
    [host] => aaa.bbb.com
    [path] => /
)

@AnjaniBarnwal,你能解释一下为什么吗?我认为这是最好的方法,如果你有一个包含URL的字符串,并且想要从https://example.com/category2/page2.html?q=2#lorem-ipsum中获取基本URL,例如https://example.com - 这与您当前所在的页面无关。 - OZZIE

7
我认为$_SERVER超全局变量包含你所需要的信息。它可能是这样的:
echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']

你可以在这里查看相关的PHP文档。

这个程序一直重定向到当前页面,我该如何修复它以重定向到主页?我使用的是Apache本地服务器和PHP7。 - Joey

6
尝试以下代码:

尝试以下代码:

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];

第一行检查您的基本网址使用的是http还是https,然后第二行用于获取主机名。第三行用于仅获取您网站的基本文件夹,例如/test_website/。

1
这个答案缺少教育性的解释。 - mickmackusa

5
简单易行的技巧:
$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path . "/";

网址看起来像这样:http://example.com/folder/


5
以下代码将简化检查协议的问题。 $_SERVER ['APP_URL'] 将显示带有协议的域名。 $_SERVER ['APP_URL'] 将返回 protocol://domain (例如:http://localhost)。 $_SERVER ['REQUEST_URI'] 用于 url 的其余部分,如 /directory/subdirectory/something/else
 $url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];

输出结果将会是这样的: http://localhost/directory/subdirectory/something/else

1
不要只是随意粘贴一堆代码,解释你做了什么以及为什么这样做。这样,原帖作者和任何未来遇到相同问题的读者都可以从你的答案中学到东西,而不仅仅是复制/粘贴它并明天再问同样的问题。 - Oldskool

5

您可以像这样操作,但抱歉我的英语不够好。

首先,使用这个简单的代码获取主页的基本网址。

我在我的本地服务器和公共服务器上测试过这段代码,结果很好。

<?php

function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');


// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];

      }

// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';

    else

// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 

}

?>

// and test it

echo home_base_url();

输出将会像这样:
local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/

在您的网站的index.php中使用home_base_url函数并定义它。

然后,您可以使用此函数通过URL加载脚本、CSS和内容。

<?php

echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";

?>

将会创建如下输出:
<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>

如果这个脚本运行良好,那么就可以!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接