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.

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

  1. Darrell

    Thank you, Roshan, for this script. Saved me lots of hassle.

    I would only change:

    if($_SERVER[‘HTTPS’]!=”on”)

    to

    if(!_SERVER[‘HTTPS’] !== “on” ) // two equals signs

    :)

  2. Darrell

    Ahh! I mistyped my correction. S/B:

    if( $_SERVER[‘HTTPS’] !== “on” ) // two equals signs

  3. Oh yes Darrel, using identical comparison operator is better than normal equality checking comparison operator…

  4. Your 3 line redirect for htaccess worked, but it broke my admin console in oscommerce. I’m trying to get a simple ecommerce website up. When I update anything using the admin console, it gives an error.

    Warning: Variable passed to each() is not an array or object in

    and then the particular path of my website. What gives?

    Sincerest Thanks!

  5. Joe

    Can someone give a example of how i need to do hide web page extension using this htaccess?

    Please explain like this:
    ===========================================================
    First create a folder called (name)
    Then paste this code into your web page between your
    rename the website name or project name in the code for yours.
    ===========================================================

    Can someone be more specific?
    Sorry guys this is my first time doing this,. Can someone help me with this?

    can someone give me something like this.

  6. Asheesh Mahajan

    This gae redirects works like a charm. My followup question is how to redirect back to http after the https work is done in a website. e.g. I have signed in and wanted to continue to browse the website in http mode and not the https mode.

  7. Asheesh Mahajan

    It works perefctly for a page. Just wanted to know how to redirect the page back to http from https. e.g. once I have logged in or accepted the credit card information wanted user to browse the website as http

  8. Ritesh

    hello everyone,
    I am having problem regarding redirect of http to https. I have checked $_SERVER[‘HTTPS’] but it return: “Notice: Undefined index: HTTPS”. How to solve this problem? I need to enable/set https or not?

    -ritesh

  9. @Chris,

    i’m sure that it is a bit late, but try to debug the code . that helps a lot for rapid prototyping.

  10. Kinder

    Great JOB!! I used it!

  11. Bleak

    How does this work for embedded content?

    i.e Images – CSS etc ?

  12. Funwebix

    Great post Roshan, small and precise.

  13. Jeff

    I’ve been using ‘if($_SERVER[‘HTTPS’]!=”on”)’ for a very long time with no issues.
    I just started noticing “PHP Notice: Undefined index: HTTPS…” in my error log.

    If I use ‘if( $_SERVER[‘HTTPS’] !== “on” )’, what should I change to stop the PHP notices? I tried addibng isset and !isset but it does not work.

    Thanks!

  14. For some reason, checking for “on” wasn’t working for me. You may have to write the code as follows:

    if($_SERVER[‘HTTPS’] == false) {
    // redirect to secure site
    }

  15. Andrew

    Jeff, You can add an @ sign before $_SERVER[‘HTTPS’]. When your not using ssl HTTPS is not defined, which is why you are getting that error. The @ sign should suppress that error.

    if(@$_SERVER[‘HTTPS’] !== “on”)

  16. Jeff

    Thanks Andrew.

    I’ve been using:

    if(empty($_SERVER[“HTTPS”])) {

    That also works but I will try the @ sign too.

  17. Falguni

    This is really nice man..thanks a lotz for this script

  18. faiza

    nice script. but my question is i writel almot 13 urls 10 of them working fine but rest of then just vanish the images and my css and js is not working anymore. i thnk it may be path problem here is that rule
    RewriteRule ^edit-uni/(.*)$ inter/index.php?file=edituni&id=$1

  19. Actually, come to think of it. You should use the 301 redirect syntax in your htaccess file as well:

    RewriteEngine On
    RewriteCond %{HTTPS} !on
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  20. Eric D

    Thank you! This is exactly what I was looking for. PERFECT! God you have to sift through so much crap to find useful stuff.

    Also, Thank you Darrell, Andrew and John for your additional improvements.

  21. Thanks, Thanks, Thanks,

    Example: http://multiatom.com/TLS/conatct.php

  22. Niranjan

    Thanks Roshan it helped me, well

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>