开发者

How server can check ajax requests not from site, X-Requested-With

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,开发者_StackOverflow社区 else)?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜