How to detect Ajax Request using PHP

If you are using PHP just drop the following line on top of your script, this will detect whether the request was made using Ajax or not. Ajax requests have usually a X-Requested-With request header, which is set by most Ajax library such as jQuery, Mootools and YUI. $_SERVER is not supported by all servers and it's not really part of PHP, they are passed by most web servers to script language and there's no guarantee that every web server will provide these headers information, hence it's good idea to check whether your server omits these headers before using this code.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
//detect ajax if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { die('Request must come from Ajax!'); }
This is the most common way to detect Ajax request in PHP, I would love to know other ways to do it, good luck!
    New question is currently disabled!