Prevent Direct Access To File Called By ajax Function

Viewed 31895

I'm calling the php code from ajax like this:

ajaxRequest.open("GET", "func.php" + queryString, true);

Since it's a get request anyone can see it by simply examining the headers. The data being passed is not sensitive, but it could potentially be abused since it is also trivial to get the parameter names.

How do I prevent direct access to http://mysite/func.php yet allow my ajax page access to it?

Also I have tried the solution posted here but its doesn't work for me - always get the 'Direct access not premitted' message.

12 Answers

I have a simplified version of Edoardo's solution.

  1. Web page A creates a random string, a [token], and saves a file with that name on disk in a protected folder (eg. with .htaccess with Deny from all on Apache).

  2. Page A passes the [token] along with the AJAX request to the script B (in OP's queryString).

  3. Script B checks if the [token] filename exists and if so it carries on with the rest of the script, otherwise exits.

  4. You will also need to set-up some cleaning script eg. with Cron so the old tokens don't cumulate on disk.

It is also good to delete the [token] file right away with the script B to limit multiple requests.

I don't think that HTTP headers check is necessary since it can be easily spoofed.

Related