How to protect ajaxRequest.open PHP script

I am new to using AJAX and I just followed the tutorial to get some information from my database using AJAX and display it on the page. There is a line where I call the php script, where the database query is executed, and the result is displayed. I'm a little worried that since the file name is visible in the external interface, and only the goal is to directly output the database results, this may pose a security problem. Is there a way to protect this file and make sure that it launches the request only when called through ajax script?

Here is the ajax code bit (note the line "somefile.php"):

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.

+4
source share
5 answers

No no. Everything that you trust JavaScript on the client side, you trust the user.

If you have authentication / authorization, you trust the users you allow. If you do not, you trust everyone and your bots.

+1
source

Put your PHP code in this check:

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

All ajax requests have this set of headers. Like all raisins, this one can also be faked, since you do not always trust anything coming from the client, filter / assign the white parameters of the incoming request and take care of your database with the help of the prepared instructions.

+1
source

You need to worry about stored xss in ajaxResponse . You can avoid this by running htmlspeicalchars($var,ENT_QUOTES); according to the data before putting them into the database or before printing them in your ajax answer.

0
source

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 is executed only after ajax call if it comes from a specific script (in the same place). Note. I test sessions and constants and did not work: /

0
source

I tried several ways to protect the called php file from direct access, and this work:

 if($_SERVER['PHP_SELF'] == $_SERVER['REQUEST_URI']) exit('This file can not be accessed directly...'); 
0
source

All Articles