views:

89

answers:

3

There is AJAX script on my WS. Is there a method to deny straight access to ajax php backend? And to access to it only if it is run from my ajax code

+2  A: 

The answer is no.

The way your ajax calls access the php scripts is just as direct as any other method.

That said, you can limit the access to your scripts in different ways, such as requiring a valid session which is created only after a login. However, once a user has logged in, accessing the backend via an ajax script or "directly" are both fair game. In other words, you cannot count on being able distinguish an ajax call from some other call at the server side.

The security of your backend needs to depend on somewhere else.

Lauri Lehtinen
+2  A: 

You can try heuristics (such as examining X-Requested-With HTTP header) but NOT as any security measure. Any such difference in how the request looks can easily be duplicated by anyone who really wants to.

ob1
+1 since this would stop the user from simply entering URL's/commands into the address bar.
thomask
Thank you. I understand.
GOsha
A: 

On server-side you can add this to the top of your backend files:

if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
  die("You need to use an AJAX request");
}

Edit: As stated by others, this is not reliable as a security measure.

Mads Jensen
Very easy to inject .. but sure.
Lauri Lehtinen