How can I prevent access to PHP files if the caller isn't using HTTPS?

I have written several PHP web services where I pass in arguments via the URL. To prevent unauthorized access, I pass in a unique key as one of the arguments. I call the PHP file via HTTPS, and I am wondering if there’s a way I can prevent the script from running if HTTPS is not used.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Slightly off topic, but if you’re using PHP with Apache Httpd and mod_ssl, you can force SSL access to files (and PHP scripts) by placing the SSLRequireSSL directive in .htaccess or in the Directory configuration.

Solution 2

if(empty($_SERVER['HTTPS'])) {
    // ....
    exit;
}

Solution 3

To clarify: You want that a client doesn’t call a url containing a secret token over a non-encrypted connection, is that right? If so, then the problem is mainly not with you, but with the browser of the client. You may redirect the client to a secure connection if he isn’t using one yet, but even if you do so the client already made an insecure, interceptable request to your server, before he get’s redirected!

Mozilla is making an effort to solve this problem. As of Firefox 4 a server may send a Strict-Transport-Security header which will prevent an unencrypted access subsequently (though obviously before the header was sent an unencrypted access could still happen.)

Further reading at hacks.mozilla.org

Solution 4

If you are using Apache, you could use mod_rewrite to redirect http requests to be https ones.

For e.g. This is what we use:

RewriteCond %{HTTPS} !=on
RewriteRule ^account(.*) https://%{SERVER_NAME}/account$1   [R=301,L]

This redirects http://domain/account to https://domain/account

Solution 5

You can prevent the server responding to an unencrypted request, but you cannot prevent the client sending it, which is just as bad for password security. And that is not by far the worst problem with putting a secret token in the URL: it remains in the browser history, it can be seen in the referer when the user leaves your site, and any website the user visits can launch a brute-force or dictionary attack via the :visited CSS pseudo-class. All in all, it is a pretty horrible idea – you are better off using SSL-only cookies.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply