views:

104

answers:

6

Hi guys, I have some pages set up so that they respond only to ajax requests. The thing is that how can I set it up so that if someone tries to send the requests via a browser window i.e by typing them out - they don't run and that they run only when an ajax call is made. The pages are in php here

+11  A: 

There's no reliabale way to distinguish an AJAX request from a normal request. Some libraries such as jQuery will append an additional X-Requested-With: XMLHttpRequest HTTP header to the request, but others might not. You could forge an AJAX request using the low level objects provided by the browser that looks exactly the same as a normal request so don't rely much.

Darin Dimitrov
Never thought about that - for now I'll just put checks for additional headers.
Ali
+5  A: 
define('XHR', (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));

If you are setting the http header with JS ( automatically done in jQuery ), use this constant.

meder
HTTP headers are easy to fake. This will only slow someone down, not stop them.
James
+2  A: 

All the information that you could check(headers, referrer, etc...) come from the browser, and can be forged.

If the user is properly authenticated(eg: through a cookie + a data token) you are not exposing more your system through a browser window than the normal ajax use.

Mic
+2  A: 

AJAX is done inside browser window. I guess you meant to prevent people from accessing it by typing an URL in the browser. You can simply use POST. Someone has to write HTML to access your page.

You can also send request in JSON, add a customized header etc.

ZZ Coder
+2  A: 

If calling the ajax url by hand (or a tool) can do something dangerous on the server there is no solution.If its for security reasons you need to secure the code that handles the ajax call. Only allow the ones which can't do any harm.

Christian
Agreed, there isn't a way to do block it, so instead fix your system so that someone doing this is not a problem.
Alex JL
A: 

There is no such stable way for this

Mazhar Ahmed