Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ajax

php

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)?

like image 606
zmol Avatar asked Feb 08 '11 04:02

zmol


People also ask

How do I know if request is AJAX request?

mypage. php: if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }

How do I know if AJAX request is successful?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

Are AJAX requests HTTP requests?

Ajax. Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method.

What type of requests does AJAX use between the server and the browser?

AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)


2 Answers

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.

like image 173
alex Avatar answered Sep 23 '22 20:09

alex


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

like image 43
AtomicAndy Avatar answered Sep 22 '22 20:09

AtomicAndy