2012-01-10 100 views
1

如何正確使用頭功能,所以PHP - 頭位置重定向:HTTPS到HTTPS,HTTP到http

header("location: http://".$_SERVER['HTTP_HOST']."/?para=abc"); //for http 

header("location: https://".$_SERVER['HTTP_HOST']."/?para=abc"); //for https 

可如果可能的話寫在1串?

.htaccess文件將負責將所有http頁面重定向到https而不會造成任何問題,但我相信在header("location:...)中爲http/https頁面使用正確的語法是有意義的,因此它適用於所有瀏覽器。

回答

4
$protocol='http'; 
if (isset($_SERVER['HTTPS'])) 
    if (strtoupper($_SERVER['HTTPS'])=='ON') 
    $protocol='https'; 

header("location: $protocol://".$_SERVER['HTTP_HOST']."/?para=abc"); 
2
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != '') { 
    header("location: https://".$_SERVER['HTTP_HOST']."/?para=abc"); 
} else { 
    header("location: http://".$_SERVER['HTTP_HOST']."/?para=abc") 
} 

這應該適用於Apache的,至少。

1

你可以做這樣的事情隔離協議類型:

$protocol = isset($_SERVER['HTTPS']) and 'https' or 'http' 

然後

header("location: $protocol://".$_SERVER['HTTP_HOST']."/?para=abc"); 
9

你也使用下面的代碼:

header("Location: //www.google.com"); 
+0

這並不爲我工作。它將URL附加到當前的根網址。 – cederlof 2017-02-05 19:41:14

0

你可以得到通過以下代碼協議:

$protocol = strtolower(substr($_SERVER[ 'SERVER_PROTOCOL' ], 0, 5)) == 'https' ? 'https' : 'http'; 

,然後重定向這樣

header('location: ' . $protocol . '://' . $_SERVER[ 'HTTP_HOST' ] . '/?para=abc');