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.
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.
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.
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.
I solved it as follows:
if($_SERVER['HTTP_REFERER'] == 'http://' . $_SERVER['SERVER_NAME'] . '/mydir/myscriptwithajaxcall.php')
// do something
else
echo 'Restricted Access';
Then the php script only be executed after the ajax call, if it comes from the specific script (same place).
Note: I test with sessions and constants and didn't work :/
i've tried few ways to protect called php file from direct access, and this work:
if($_SERVER['PHP_SELF'] == $_SERVER['REQUEST_URI'])
exit('This file can not be accessed directly...');