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.
The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.
Approach 1: Check if the connection is using SSL and if the value of $_SERVER['HTTPS'] is set, then we can say that the connection is secured and called from 'HTTPS'. If the value is empty, this means the value is set to '0' or 'off' then we can say that the connection is not secured and the page is called from 'HTTP'.
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(empty($_SERVER['HTTPS'])) {
// ....
exit;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With