The Elusive $_SERVER['HTTP_X_REQUESTED_WITH'] in PHP
AJAX requests have become ubiquitous on the web, and discerning whether a request is AJAX or not can be crucial for optimizing code execution. In PHP, it has been conventionally recommended to check for the existence of $_SERVER['HTTP_X_REQUESTED_WITH'].
However, this variable is mysteriously absent from the official PHP documentation. Attempts to access it return nothing, casting doubt on its availability.
Unveiling the Hidden Variable
In reality, the variables in $_SERVER are external to PHP itself, injected by the web server. The X-Requested-With header, which indicates an AJAX request, is commonly sent by major frameworks.
Cautionary Notes
While $_SERVER['HTTP_X_REQUESTED_WITH'] can be a useful indicator, it's not universally reliable. Some frameworks may not always send this header, leaving you with false positives or negatives.
A Surefire Solution
For absolute certainty, the only foolproof way to distinguish AJAX requests is to define a specific flag (e.g., a GET variable) that accompanies the request and check for its presence on the receiving page.
The above is the detailed content of Why is $_SERVER[\'HTTP_X_REQUESTED_WITH\'] Missing from PHP Documentation, and How Can I Reliably Detect AJAX Requests?. For more information, please follow other related articles on the PHP Chinese website!