abhishek
abhishek

Reputation: 11

How do I force HTTPS on a some pages? (PHP)

I have a single PHP file which handles credit card processing. It starts as a form to input the credit card number, then becomes a "confirm" screen (showing the credit card number) then once more to process and display the results. All three loads will be done with PHP submits (I realize the confirm might be better as Javascript, but I didn't write it). It is the only file in the directory which handles credit cards, and therefore it is the only one which needs httpS connection.

I have tried forcing this with the $_SERVER array, looking up the protocol used to connect from the prefix of the SCRIPT_URI (or other entry), but none had the prefix.

Is there a simple way to do this...i want ssl on 5 pages homepage, login, register, contact page and if user visit other page then he should be on non ssl version

Sorry for the questions, but my searches thus far here haven't uncovered a working solution, and I'm afraid I don't know what the best practice is.

Upvotes: 0

Views: 1684

Answers (3)

Sérgio Martins
Sérgio Martins

Reputation: 112

Use this code on php pages you want:

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

Upvotes: 3

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Suppose you want to redirect 4 specific pages to https,

  • page1.php
  • page2.php
  • page3.php
  • page4.php

then you would do something like this:

Create a .htaccess file in your root directory and add the following lines to it.

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

#redirect www.yourdomain.com to yourdomain.com (or any other subdomain)
RewriteCond %{HTTP_HOST} !^yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]

#force https for certain pages    
RewriteCond %{HTTPS} !=on
RewriteRule ^(page1\.php|page2\.php|page3\.php|page4\.php)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

Upvotes: 0

maxhb
maxhb

Reputation: 8865

You should investigate $_SERVER['HTTPS']. This will have a non empty value if https is used and an empty value otherwise.

If you detect a non https connection you can redirect the user, e.g. using php header() method.

Another way to achieve this would be to use .htaccess configuration (if you're running on apache web server):

RewriteCond %{HTTPS} !=on
RewriteRule ^creditcard\.php$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

Using https for the whole website is a really good option, too.

Upvotes: 0

Related Questions