Monday, April 9, 2012

HTTP to HTTPS in PHP not working solutions

While searching for making your URL from http to secured https you will find dozens of links telling you to write the following:


if($_SERVER['HTTPS']!="on")
  {
     $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
     header("Location:$redirect");
  }



If you haven't even tried that then try it and you will be good to go.
If however that doesn't workas it didn't in my case, , and dumping $_SERVER variable doesn't give you HTTPS element in array either if its http or https then then you can have either of the two problems:

1. Your host is using some shared SSL certificate which uses the same port of 80 as for http and handling security itself, for that you would need to request your host to enable $_SERVER['HTTPS']

2. My case was even different. My client's website is on cloud hosting (something new at this point in time) and apparently it works somewhat different then others and has the array element $_SERVER["HTTP_X_FORWARDED_PROTO"] set to value "https" so the fix for me was:


if (!$_SERVER["HTTP_X_FORWARDED_PROTO"]=="https") {
    $newurl = "https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    header("Location: $newurl");
    exit();
}

No comments:

Post a Comment