+91-943-185-6038 me@shashidharkumar.com

Most of the e-commerce website uses payment gateway for online payment. And, those sites uses SSL (secure socket layer) connection to transfer data to and from the payment gateway.

Most of the sites uses “http” protocol and you can see “http” in the browser’s address bar. But in the Ssl connection, we need to redirect the browser to “https” which means that “Hypertext Transfer Protocol over Secure Socket Layer”.

How to redirect the browser to https in PHP?

First of all, you must be installed SSL in the server. To redirect the browser to “https”, we must know that the site is using SSL or not at the moment. And for this, there is a server variable in PHP called “HTTPS”. $_SERVER[‘HTTPS’] returns “on” values when the site is using SSL connection.

Function to redirect the browser to “https” in PHP

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

Above function is quite simple, you can call the function in that page where you’ve to redirect the browser to “https”.

Redirecting whole website to “https” using .htaccess

You can call the above function in each and every page to redirect the browser to “https”. But rather than doing so it will be better to write three line of code in .htaccess file to redirect the whole website to use SSL connection throughout the pages.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
See also  50+ PHP tips and tricks