2011-11-04 110 views
1

我想獲取當前網頁的網址。這裏是代碼:PHP當前網址問題

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; 

它工作正常。但是我處理問題:

<a title="LT" href="<?php echo $url; ?>?lang=lt">LT</a> 

當我按下「LT」鏈接再次,它給我的結果是:

http://127.0.0.1/index.php?lang=lt?lang=lt 

如何避免這種情況?

+0

你知道你已經傳遞了變量$ _Server ['SERVER_NAME'] – NoPHPknowldege

回答

4

$_SERVER['REQUEST_URI']包括查詢字符串域後返回的一切(嗯......不是萬能的,因爲它不能返回碎片...)如果你想使用$_SERVER['REQUEST_URI'],那麼你可能會爆炸它像這樣

$uri = explode('?', $_SERVER['REQUEST_URI']); 
$uri = $uri[0]; 

然後使用$uri變量代替$_SERVER['REQUEST_URI']這樣的:

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$uri : "http://".$_SERVER['SERVER_NAME'].$uri; 
0

我發現這段代碼非常有幫助

$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === 
FALSE ? 'http' : 'https';   // Get protocol HTTP/HTTPS 
$host  = $_SERVER['HTTP_HOST']; // Get www.domain.com 
$script = $_SERVER['SCRIPT_NAME']; // Get folder/file.php 
$params = $_SERVER['QUERY_STRING'];// Get Parameters occupation=odesk&name=ashik 

$currentUrl = $protocol . '://' . $host . $script . '?' . $params; // Adding all 

echo $currentUrl;