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)?
mypage. php: if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }
$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With