简体   繁体   中英

Prevent direct access to file through AJAX call

I'm breaking my head over this issue, where I want to prevent people from direct accessing a file which I'm calling using AJAX.

In short:

  • main-script.php makes an AJAX call to ajax-request.php
  • ajax-request.php can only be called from from main_script.php
  • Prevent direct access to ajax-request.php

I've already read similiar questions like this one , but the "accepted answer" here (like many other of the answers) seems like it shouldn't be accepted. What got my attention however was this answer , where he's talking about using $_SESSION and hashing. Now the problem is (1) that I'm skeptical if you can actually prevent people from direct accessing in this case; (2) I can't wrap my head around on how you'd use sessions and hashing to make this happen.

So I would appreciate it if someone could help me out with the thinking process or give me a push in the right direction (or give advice if it's not really possible at all).

You can't prevent me from requesting yourdomain/ajax-request.php as long as I know there is some resource on that location, however you can prevent unauthorized access to this file, similar to the way to prevent guests from members areas on your website, or any resource that requires authorization. The deference is that I don't get an authorized access by providing a password , no I get that access to ajax-request.php only if I requested main_script.php

The simplest way I would do to accomplish this is with ( $_COOKIE and database) or ( $_SESSION ), for example

main_script.php

$_SESSION['canRequestAjax'] = 1;

other_scripts.php

unset($_SESSION['canRequestAjax']);
/* 
 remove the variable if he visited something else, 
 because he can only request the ajax-request.php RIGHT AFTER the main_script.php
*/

ajax-request.php

if (empty($_SESSION['canRequestAjax'])){
    die('error'); // TODO: proper 403 response
}
unset($_SESSION['canRequestAjax']);
/* 
 remove the variable if he requested the ajax ajax-request.php file, only 1 ajax is allowed. 
NOTE: remove this line if the user may do more than 1 ajax requests when he is on
 main-script.php
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM