How to force (https) SSL to load when a user is on http in PHP?

View QuestionsCategory: CodeHow to force (https) SSL to load when a user is on http in PHP?
admin Staff asked 4 years ago

This is especially useful now that most websites are expected to adopt SSL as a standard.

1 Answers
admin Staff answered 4 years ago

Use one of the two code snippets below:

if($_SERVER['SERVER_PORT'] != 443) {
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   exit();
}

Or this one:

if(!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on") {
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: https://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
   exit();
}