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.
if ($_SERVER['SERVER_PORT']!=443) {
/* Do something / report something / redirect user to https version */
exit;
}
The $_SERVER['HTTPS']
variable may also work in your case - but according to comments in PHP documentation it may not work across all servers (it's a property set by the webserver after all... appears to work with Apache, but not sure about IIS, Nginx, lighttp, etc)
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.
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
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.)
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.