0

Hy there, I'm using this php code to check if a request is made via ajax:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {echo 'is ajax';}

This code works for me until today when start fail most of the time. I have check the $_SERVER['HTTP_X_REQUESTED_WITH'] with an echo and sometimes return XMLHttpRequest most of the time return nothing and sometimes return this XMLHttpRequestOl .

After a long search i found this answer and using that code the xmlhttprequest is returned every time an ajax request test passed.

Can anyone explain why this behaviour ?

Thanks a lot and have a nice day everyoane!

The output for apache_request_headers() :

["Host"]=>
  string(9) "example.com"
  ["Connection"]=>
  string(10) "keep-alive"
  ["Accept"]=>
  string(46) "application/json, text/javascript, */*; q=0.01"
  ["Origin"]=>
  string(16) "http://example.com"
  ["X-Requested-With"]=>
  string(14) "XMLHttpRequest"
  ["User-Agent"]=>
  string(109) "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"
  ["Referer"]=>
  string(23) "http://example.com"
  ["Accept-Encoding"]=>
  string(13) "gzip, deflate"
  ["Accept-Language"]=>
  string(35) "ro-RO,ro;q=0.8,en-US;q=0.6,en;q=0.4"
  ["Cookie"]=>
  string(36) "PHPSESSID=0c3vufj32s6v47o2oq38cj2rh2"

The apache version is

Server version: Apache/2.4.10 (Debian)
Server built:   Nov 28 2015 14:05:48
Server's Module Magic Number: 20120211:37
Community
  • 1
  • 1
thenutz
  • 75
  • 1
  • 10

1 Answers1

0

Try to check X-Requested-With header to determine Ajax request. It is known to work with common JavaScript frameworks:

$headers = getallheaders();
if ('XMLHttpRequest' == $headers['X-Requested-With']) {
   // This is Ajax request!
}

Symfony uses this way to check XML HTTP request in their Request::isXmlHttpRequest().

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
  • Right now i'm using $headers = apache_request_headers(); if(isset($headers['X-Requested-With']) && strtolower($headers['X-Requested-With']) == 'xmlhttprequest') { echo 'is ajax';} I will try with getallheaders(); too. Thanks – thenutz Feb 24 '16 at 10:26
  • `getallheaders()` function is an alias for `apache_request_headers()`, I like to use it more due to its name. – Victor Bocharsky Feb 24 '16 at 10:28