0

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.

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

it works for direct access, but for some reason it did not work with the javascript it still dies
@RussellHarrower See also: stackoverflow.com/questions/2579254/… for additional information about HTTP_X_REQUESTED_WITH
What if someone simply creates a custom HTTP request containing X-Requested-With?
@Gumbo You can always check referer
The Referer can be faked just as any other header field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.