How do I force HTTPS on a single file? (PHP)

10,331

Solution 1

At the beginning of the PHP page that does all your credit card processing, you can add this:

It will redirect back to itself, except using https if it was first loaded over http. Of course you still need an SSL certificate installed for your domain.

if (!isset($_SERVER['HTTPS']) || !$_SERVER['HTTPS']) { // if request is not secure, redirect to secure url
    $url = 'https://' . $_SERVER['HTTP_HOST']
                      . $_SERVER['REQUEST_URI'];

    header('Location: ' . $url);
    exit;
}

I use this same logic in PHP to secure my entire domain by putting that in file that is always called at the beginning of every request for my site.

Solution 2

Place the following code in a .htacces file in your folder:

RewriteEngine On
RewriteCond %{SERVER_PORT} !443
RewriteRule (.*) https://www.example.com/require-secure/ [R]

It fires if the port is NOT 443 (443 is for HTTPS) and redirects to https://www.example.com/require-secure/.

Note: mod_rewrite is needed but mostly available

Solution 3

First off, why would you want to purposefully make all of your site use an unsecured protocol? Do you really have such a tight performance budget that you can't stomach the overhead of TLS? Premature optimization is the bane of mankind.

Also, saying that the credit-card-processing script is the only one which needs HTTPS implies that your user login system is sending passwords in the clear. That's not just performance-greedy, it's downright poor design.

That aside, the right solution is to use mod_rewrite to force a redirect to HTTPS for that link. An alternate solution if you don't have the ability to manipulate the server config at all (even via .htaccess) is to have your PHP script check the protocol first thing, and if it's not HTTPS issue a redirect and terminate.

Share:
10,331
Bing
Author by

Bing

Updated on June 05, 2022

Comments

  • Bing
    Bing almost 2 years

    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 tried enforcing 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 with the .htaccess file in the same directory? How do I enforce it for ONLY that one file? If there's any other simple way, how would I do it?

    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.

    Thanks!