tags:

views:

34

answers:

3

I'm new to using AJAX, and I just followed a tutorial to retrieve some info from my database using AJAX and outputting it on the page. There's a line where I call a php script which is where the database query is made, and the result is echoed out. I'm a little concerned that since the filename is visible on the frontend, and it's only purpose is to directly output database results, it might present a security issue. Is there any way to protect that file, and make sure it only runs the query when called via the ajax script?

Here's the bit of ajax code in question (note the "somefile.php" line):

ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        var ajaxResponse = ajaxRequest.responseText;
        element.innerHTML = '<h2>' + ajaxResponse + '</h2>';
    }
}
ajaxRequest.open("GET", "somefile.php", true);
ajaxRequest.send(null);

Thanks for any answers.

+1  A: 

No, there isn't. Anything you trust to client side JavaScript, you trust to the user.

If you have authentication/authorization, then you trust the users that you authorize. If you don't, then you trust everybody and their bots.

David Dorward
you can also create a single use security token and insert it into the ajax request and then have php check for the correct token. it's by no means unbeatable, but it'll filter out some of the noise
pxl
Indeed (although that does fall under the heading of "authorize" :)
David Dorward
A: 

Put your PHP code within this check:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
    /* Your code here */
    }

All ajax requests do have this header set. As all heasers this one too might be forged, so as always don't trust anything coming from the client, filter/whitelist the incoming request parameters and take care of your database using prepared statements.

djn
This is not true if you are making Ajax calls manually. Mainstream frameworks add some kind of header like this, but this is not always true, and if you are making it manually, you'll need to set them yourself.
Dave
A: 

You have to worry about stored xss in the ajaxResponse. You can avoid this by doing an htmlspeicalchars($var,ENT_QUOTES); on the data before you put it into the database or before your print it out in your ajax response.

Rook