Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force HTTPS on a single file? (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 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!

like image 250
Bing Avatar asked Jan 18 '26 03:01

Bing


1 Answers

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.

like image 175
drew010 Avatar answered Jan 19 '26 18:01

drew010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!