How to redirect browser to https (ssl) in php

How to redirect browser to https (ssl) in php

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.

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

Ok let’s see a real example, type “http://www.gmail.com” in browser after a while the “http” gets converted to “https” in address bar, which means this site is transferring the data over SSL protocal.

How to redirect the browser to https when site is using http protocal in PHP?

First of all, you should know that SSL must be installed 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” .This function will preserver you script file name and query string in browser.

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} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Just copy and paste the above code in .htaccess file then the whole website will be redirected to “https” when the browser is opened in “http” mode. The browser just get redirected using url rewriting in .htaccess.

Related Posts


3 thoughts on “How to redirect browser to https (ssl) in php

  1. Vern Buttross

    Good day! I simply wish to give a huge thumbs up for the nice data you have got here on this post. I will probably be coming again to your blog for extra soon.

    Reply
  2. kore dizileri izle

    Great one particular webpage operator achievements weblog post fantastic sharings in this blog usually have enjoyable

    Reply
  3. Edmundo Matteo

    I just want to say I am just new to blogs and actually savored you’re web blog. Very likely I’m planning to bookmark your blog . You actually have good posts. Appreciate it for sharing your web page.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*