Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does $_SERVER['HTTP_X_REQUESTED_WITH'] exist in PHP or not?

All over the Internet, included even here at Stack Overflow, people state that a good way to check if a request is AJAX or not is to do the following:

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {...} 

However, I don't see $_SERVER['HTTP_X_REQUESTED_WITH'] in the official PHP documentation

And when I try to do the following:

echo $_SERVER['HTTP_X_REQUESTED_WITH']; 

Nothing is outputted.

Am I doing something wrong? Because I'd really like to be able to use $_SERVER['HTTP_X_REQUESTED_WITH'] if it's available.

like image 880
Hank Avatar asked Apr 05 '10 15:04

Hank


2 Answers

The variables in $_SERVER are not really part of PHP, which is why you won't find them in the PHP documentation. They are prepared by the Web server which passes them on to the scripting language.

As far as I know, the X-Requested-With is sent by the Ajax functions of most major Frameworks but not all (Dojo, for example, added it only two years ago: #5801). As such, and taking into considerations @bobince' comments, it's safe to say it's not generally a 100% reliable method to determine whether a request is an AJAX request or not.

The only 100% secure way is to send a pre-defined flag (e.g. a GET variable) along with the request and for the receiving page to check for the presence of that flag.

like image 73
Pekka Avatar answered Oct 14 '22 12:10

Pekka


don't forget that you can easily spoof any header with cURL like so

curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-Requested-With : XMLHttpRequest")); 
like image 22
J. Michael Wilson Avatar answered Oct 14 '22 13:10

J. Michael Wilson