I read that checking the X-Requested-With header of the ajax request is a good way to make sure the request isn't coming from outside. On the server side, how do I check this header? and what's the right way to react of this header is missing or wrong (redirect, throw exception, else)?
Asked
Active
Viewed 7,445 times
5
-
4You might want to look at http://stackoverflow.com/questions/623299/can-the-x-requested-with-http-header-be-spoofed; it shows that `X-Requested-With` can be spoofed. – Jeremiah Willcock Feb 08 '11 at 04:06
-
you want to see this also http://www.yiiframework.com/forum/index.php?/topic/4945-yiiapp-request-isajaxrequest/ – Netorica Sep 20 '12 at 03:40
2 Answers
8
You can check it like this...
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
If you are only expecting access via XHR, then just exit
if this header is not present.
Note: This header is trivial to spoof. Don't rely on this for anything but it looks like it came from na XHR.

alex
- 479,566
- 201
- 878
- 984
-
I want to use it to make sure that the request isn't coming from someone who looked at my js code, took the urls and is submitting input from outside my site. So if it can be faked, then there's no way to protect from this? – zmol Feb 08 '11 at 04:50
-
@zmol I'm sorry, there is no way by just looking for the presence of that header. – alex Feb 08 '11 at 05:03
-
but are there other ways? It does not have to be through this header. The end goal is to make sure that the request isn't coming from someone who read the js code, read the ajax url line, and is playing the url from outside :) – zmol Feb 08 '11 at 05:09
-
-
this method doest work if javascript doest send xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); ? – zloctb Sep 15 '13 at 22:06
6
The only sure fire way to ensure that the request came from your site and not someone else's is to issue a unique token to the user and store it in their session. In your code where you make the AJAX request you then need to pass this token back and if it matches the one in their session then you can be sure the request came from your site.
More info: http://en.wikipedia.org/wiki/Cross-site_request_forgery

AtomicAndy
- 61
- 1
- 1