简体   繁体   中英

block direct access to PHP file and only allow local javascript to access it

I need a way to block all access to a php file but to allow a javascript file that send xmlhttp request to it. that js file is hosted on my server and must stay on my server for it to work

I have the following

header('Access-Control-Allow-Origin: *');

but that allows anyone to access it.

Well, I don't think this would be possible. Anyone can make a request to your server but your server chooses who to respond to and how to respond to a request. Now, if you want only your JS to be responded to by your server, then you will have to inform the server at the time of making an HTTP request from your JS. That cannot be done without exposing your Javscript file's identity on the basis of which your JS can be identified by the server. But anyone can open your JS and read it and figure out how you are making the request and use the same thing.

One possible solution could be, use header('Access-Control-Allow-Origin: *') to allow everyone to make a request to your server but at the server's end, keep a list of allowed domains/origins in a database on your server who may use or are going to use your JS file on their website. Based on the AJAX request that you get, you check from your database that if the origin of the request is allowed or not and respond accordingly. Now, if someone tries to request your PHP file by any other means than your JS, on the basis of the data in your DB you can reject the request or accept the request. If an allowed user/website does this, then they will be knowingly messing around with their own data.

Try this:

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) <> 'xmlhttprequest') 
{ 
    die('direct access is not allowed'); 
} 

Also, you can always check referrer like $_SERVER['HTTP_REFERER'] to be sure that only your script from your domain can access it.

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