Forcing Secure Mode Using PHP

Here is an easy way to make sure that a user is loading the current page in secure mode. Using the PHP server array we can check to see if the page is being loaded via port 443 which is the SSL port. If not then we redirect the page back to itself adding the https:// to the current url. In addition, the code sends a 301 for the previous page so that if it is cached in the search engines they will update their outdated link.

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

Ready to start your project?

Scroll to Top