|
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.
|