2011-03-07 205 views
19

我使用下面的代碼獲取當前URL獲取當前URL

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

是否有任何其他的方式來獲得相同的,或者可能是更好的方法來獲取當前URL?

謝謝。

回答

33

the reference

<?php 

function curPageURL() { 
    $pageURL = 'http'; 

    if ($_SERVER["HTTPS"] == "on") { 
     $pageURL .= "s"; 
    } 
    $pageURL .= "://"; 

    if ($_SERVER["SERVER_PORT"] != "80") { 
     $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; 
    } else { 
     $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
    } 

    return $pageURL; 
} 
?> 
+0

我相信你必須小心檢查HTTPS值,因爲它在Apache和IIS之間有所不同。 – Jacob 2011-03-07 05:43:01

+0

@Jacob是的,並閱讀文章的空間和IIS – diEcho 2011-03-07 05:43:46

+1

文章真的很好 – 2011-03-07 09:26:01

8

你必須要小心依靠服務器變量,它取決於Web服務器想給你什麼......這是一個相當故障安全的方式來獲得的URL。

$url = ''; 

if (isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) 
    $url .= 'https'; 
else 
    $url .= 'http'; 

$url .= '://'; 

if (isset($_SERVER['HTTP_HOST'])) 
    $url .= $_SERVER['HTTP_HOST']; 
elseif (isset($_SERVER['SERVER_NAME'])) 
    $url .= $_SERVER['SERVER_NAME']; 
else 
    trigger_error ('Could not get URL from $_SERVER vars'); 


if ($_SERVER['SERVER_PORT'] != '80') 
    $url .= ':'.$_SERVER["SERVER_PORT"]; 

if (isset($_SERVER['REQUEST_URI'])) 
    $url .= $_SERVER['REQUEST_URI']; 
elseif (isset($_SERVER['PHP_SELF'])) 
    $url .= $_SERVER['PHP_SELF']; 
elseif (isset($_SERVER['REDIRECT_URL'])) 
    $url .= $_SERVER['REDIRECT_URL']; 
else 
    trigger_error ('Could not get URL from $_SERVER vars'); 

echo $url;