Disable Direct Access to a Script With PHP
A question was asked in the comments for "Make Your Own Ajax Contact Form" about preventing a PHP script from being accessed directly.
This can be done for security reasons. In the example of the Ajax contact form tutorial, it would be to prevent potential spammers from taking advantage of a security vulnerability.
Here is one simple way to disable direct access to a script: Insert the following at the top of your PHP script.
if (!defined('BASEPATH') exit('Nothing to see here.'); |
It's quite simple, really. First, it checks to see if a constant is not defined. In this case it is BASEPATH, which should not be defined if the script is being accessed directly.
If that condition is true, it means that the script is being accessed directly. In that case, it uses the exit function to stop the script and display a message upon exiting.
Using This With Ajax
In the example of an Ajax contact form, this does not work. So, we'll have to modify that line of code a bit. Mainly by inserting more conditions into the if statement.
if (!defined('BASEPATH') && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') exit('Nothing to see here.'); |
First, it checks for the existence of a BASEPATH constant, like before. Next, it checks what was used to request the page. If it's not "xmlhttprequest" (Ajax), it continues on. The strtolower function is used to make sure that there are no problems with capitalization.
Finally, if all those conditions are true, the script stops with a message.
This answers my question perfectly. I appreciate your hard work in getting and posting this information.
Have a great day!
I have to wonder if there is any way to spoof the $_SERVER['HTTP_X_REQUESTED_WITH']...
Thanks I was looking for that.
But in my application I have some page that are get by iframe, so i've add one more line and it's appear to work as i want:
if (!defined('BASEPATH') &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
if ($_SERVER['HTTP_REFERER'] != "http://---adress of my homepage---") {
exit('Nothing to see here.');
}
}
Great code! but both pieces of code need the closing )
if (!defined('BASEPATH') exit('Nothing to see here.');
needs to be
if (!defined('BASEPATH')) exit('Nothing to see here.');
and so on.
heheheh.....
i wonder, how we should send "xmlhttprequest" to the restricted page?
You might want to change it to or instead of and in your if statement.
If HTTP_X_REQUESTED_WITH can be spoofed, then all someone needs to do is spoof if and it will bypass the defined check.
That saved my day! Thanks for sharing this :)
Man! you are awesome! Thanks for the shared snippets! Thank you Eric Bannatyne!