บังคับเว็บไซต์ใช้ SSL ด้วย .htaccess หรือ php Redirect to https (SSL) in php


หน้าแรก PHP MySQL เกร็ดความรู้ บังคับเว็บไซต์ใช้ SSL ด้วย .htaccess หรือ php Redirect to https (SSL) in php
Hello Friends !!

Today I found some new things. This post is show you how to redirect to https(SSL) in PHP.

First, What is SSL ? Let me Explained :

SSL meand Secure Socket Layer. It is developed by Netscape to transmit private data via Internet.

SSL uses a cryptographic system that uses two keys to encrypt data – a public key known to everyone and a private or secret key known only to the recipient of the message. Both Netscape Navigator and Internet Explorer support SSL, and many Web sites use the protocol to obtain confidential user information, such as credit card numbers. By convention, URLs that require an SSL connection start with https: instead of http:

Most of e-commerce sites uses payment gateway for online payment.And those sites use SSL connection to transfer data to and from the payment gateway.

Most of the sites use http protocol. But in above case wehave to redirect browser to https.
If you want to see example, write “http://www.gmail.com” in browser, it automatically redirects to https.It means site transfer to SSL protocol.

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.


PHP function to redirect browser to “https”

function redirectTohttps()
{
if($_SERVER['HTTPS']!=”on”)
{
$redirect= “https://”.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header(“Location:$redirect”);
}
}
?>
you can call the function in that page where you have to redirect the browser to “https”.

Redirect website to “https” using .HTACCESS

You have to call above function in each and every page if you want to redirect whole sote. But rather than doing so it will be better to write code in .htaccess file to redirect the whole website to use SSL connection throughout the pages.Here is the .htaccess code :

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Just copy this code in yuor .htaccess file and place it in your root directory. Whole site will be redirected to “https” when browser will open with “http”.

If you have any query or any question then please comment on this post.

Thanks in Advance….



ขึ้นไปด้านบน