Using $_SERVER['HTTP_X_REQUESTED_WITH'] to Detect AJAX Requests
One widely used method for determining if a request is an AJAX request is checking for the presence of the $_SERVER['HTTP_X_REQUESTED_WITH'] variable.
Confusion Regarding Variable Existence
However, some users report that this variable is not defined in the PHP documentation or doesn't produce any output when echoed. This has led to questions about its existence and validity.
Explanation
The variables found in $_SERVER are not part of PHP itself but are instead passed to the scripting language by the web server. This is why you may not find them documented in the PHP docs.
HTTP_X_REQUESTED_WITH Header
The HTTP_X_REQUESTED_WITH header is sent by most major Ajax framework functions. However, some exceptions exist, making it unreliable as a 100% accurate indicator of AJAX requests.
Alternative Method
To reliably determine whether a request is an AJAX request, it's recommended to send a predetermined flag, such as a GET variable, along with the request and check for its presence on the receiving page. This ensures more accuracy in detecting AJAX requests.
The above is the detailed content of How Can I Reliably Detect AJAX Requests in PHP?. For more information, please follow other related articles on the PHP Chinese website!