Home >Backend Development >PHP Tutorial >Is $_SERVER[\'HTTP_X_REQUESTED_WITH\'] a Reliable Way to Detect AJAX Requests in PHP?

Is $_SERVER[\'HTTP_X_REQUESTED_WITH\'] a Reliable Way to Detect AJAX Requests in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 22:03:11820browse

Is $_SERVER['HTTP_X_REQUESTED_WITH'] a Reliable Way to Detect AJAX Requests in PHP?

Controversy Surrounding $_SERVER['HTTP_X_REQUESTED_WITH'] in PHP

While extensively suggested online, including on Stack Overflow, it's crucial to address the debated existence of $_SERVER['HTTP_X_REQUESTED_WITH'] in PHP.

Contrary to popular belief, this variable is not explicitly mentioned in PHP's official documentation. Moreover, attempts to access it might result in no output, leading to confusion among developers.

Clarification

The variables in $_SERVER are not inherent to PHP but are provided by the web server and passed on to the scripting language. Specifically, the X-Requested-With header is added by Ajax functions in various frameworks. However, its presence is not universally consistent.

Reliability as an AJAX Indicator

Due to potential inconsistencies, using $_SERVER['HTTP_X_REQUESTED_WITH'] to determine if a request is AJAX is not 100% reliable. It's possible for the header to be absent even for legitimate Ajax requests.

Alternative Approach

To ensure accurate identification of Ajax requests, it's recommended to transmit a predetermined flag (e.g., a GET variable) along with the request. The receiving page should then verify the presence of this flag. This method provides a more reliable and secure solution.

The above is the detailed content of Is $_SERVER[\'HTTP_X_REQUESTED_WITH\'] a Reliable Way to Detect AJAX Requests in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn