2023-04-22 08:00:05

获取完整的PHP URL

我使用这段代码来获得完整的URL:

$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

问题是我在我的.htaccess中使用了一些掩码,所以我们在URL中看到的并不总是文件的真实路径。

我需要的是得到URL, URL中写了什么,不多不少——完整的URL。

我需要得到它如何出现在web浏览器的导航栏,而不是服务器上文件的真实路径。


当前回答

非常简单的用法:

function current_url() {
    $current_url  = ( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
    $current_url .= ( $_SERVER["SERVER_PORT"] != 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
    $current_url .= $_SERVER["REQUEST_URI"];

    return $current_url;
}

其他回答

看一下$_SERVER['REQUEST_URI'],即

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

(注意双引号字符串语法是完全正确的)

如果你想同时支持HTTP和HTTPS,你可以使用

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

编者注:使用此代码具有安全隐患。客户端可以将HTTP_HOST和REQUEST_URI设置为它想要的任意值。

使用Apache环境变量很容易做到这一点。这只适用于Apache 2,我假设您正在使用Apache 2。

简单使用下面的PHP代码:

<?php
    $request_url = apache_getenv("HTTP_HOST") . apache_getenv("REQUEST_URI");
    echo $request_url;
?>

我使用了下面的代码,它对我来说工作得很好,对于HTTP和HTTPS这两种情况。

function curPageURL() {
  if(isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on' )) {
        $url = 'https://'.$_SERVER["SERVER_NAME"];//https url
  }  else {
    $url =  'http://'.$_SERVER["SERVER_NAME"];//http url
  }
  if(( $_SERVER["SERVER_PORT"] != 80 )) {
     $url .= $_SERVER["SERVER_PORT"];
  }
  $url .= $_SERVER["REQUEST_URI"];
  return $url;
}

echo curPageURL();

Demo

这是你问题的解决方案:

//Fetch page URL by this

$url = $_SERVER['REQUEST_URI'];
echo "$url<br />";

//It will print
//fetch host by this

$host=$_SERVER['HTTP_HOST'];
echo "$host<br />";

//You can fetch the full URL by this

$fullurl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $fullurl;

简单的使用方法:

$uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']