Securing your ajax scripts

Here’s a few tricks I’ve learnt while working on a project:


Referrals are tricky. They cannot be trusted. A small, but effective check is for HTTP_X_REQUESTED_WITH.

if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') die('no direct access allowed');

This prevents users from accessing the URL directly in the browser.

2. Put a time limit between requests, even as small as 2 seconds. In my particular project, an action took exactly 5 seconds so I checked for requests to be made at 3 or 4 seconds apart.

You can achieve this by setting in the session the value of time() of when your last request was done and check like this:

if (!empty($_SESSION['last']) && time()-$_SESSION['last']<4) die('please cool off');

There are no comments yet, add one below.

Leave a Comment

Your email address will not be published. Required fields are marked *