allow cross domain ajax requests

As mentioned above, anyone can send a request to you page at any time: so the major security concerns you need are to validate user input and only reveal information that is available for public consumption. But that applies to all scripts.

The two main issues you need to concentrate on (after validating user input) are:

  1. The problem you may have is users receiving the information into their scripts. Depending on the browser (and even between flavours of the same browser) there are different security rules that prevent them from getting the information back. A common solution to this is to provide information back as “JSONP” which is to wrap your return value as a function call that can be executed by the client. Here’s a quick example (taken from http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/). To further lock it down, you can insist that all queries are JSONP and reject anyone not sending the callback function.

.

<?php

header('content-type: application/json; charset=utf-8');
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo $_GET['callback'] . '('.json_encode($data).')';

?>
  1. Someone abusing your service by calling too regularly. Solutions for this are to trap the IP address and reject if you get too many calls from an IP address. Not foolproof, but it’s a start.

Other factors to bear in mind:

  • cookies and other headers set by your script will probably be ignored
  • same applies to sessions

Leave a Comment