php - header location redirect: https to https, http to http

跟風遠走 提交于 2019-12-08 01:16:27

问题


How do I properly use header function, so

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

and

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

could be written in 1 string if possible?

.htaccess file will take care of all http pages to be redirected to https with no problem, but I believe it makes sense to use a proper syntax for http/https pages in header("location:...), so it is correct for all browsers.


回答1:


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

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



回答2:


You could also use the following code:

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



回答3:


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

This should work for Apache, at least.




回答4:


You can isolate the protocol-type by doing something like this:

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

Then

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



回答5:


You can get the protocol by following code:

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

and then redirect like this

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


来源:https://stackoverflow.com/questions/8801340/php-header-location-redirect-https-to-https-http-to-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!