Monday, 27 May 2013
Facebook StumbleUpon Twitter Google+ Pin It

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 exitfunction 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.

No comments: