2

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.

5 Answers 5

10

You could also use the following code:

header("Location: //www.google.com");
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for me. It appends the URL to the current root url.
4
$protocol='http';
if (isset($_SERVER['HTTPS']))
  if (strtoupper($_SERVER['HTTPS'])=='ON')
    $protocol='https';

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

Comments

2
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.

Comments

1

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");

Comments

0

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' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.