PHP native method to determine whether it is an ajax submission: 1. Create a php sample file; 2. When making an ajax request, set a variable for the file header information; 3. Determine whether the information exists on the php side And if it is equal to the value you set, you can know whether it is an ajax request.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
How to judge whether it is an ajax submission in native php?
Idea: When you make an ajax request, set a variable for the file header information, and use the PHP side to determine whether this information exists and whether it is equal to the value you set, so you can know whether it is an ajax request. .
Method: js side sends header information
Object.setRequestHeader("Variable name", "Variable value");
For example, xmlHttp..setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
php side accepts information, please note that the variables accepted at this time exist in $_SERVER['HTTP_variable name'];,
As in the above example, it is $_SERVER ['HTTP_X_REQUESTED_WITH'];
echo isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest')?'it is ajax':'it is not ajax ';
Note: There are slight differences between js and jquery, please pay attention to it yourself, and don't conflict with variable names
Additional: If this is your own website, you just need to distinguish it yourself If so, this is fine, but it cannot prevent others from stealing your ajax data, because these can be simulated. A good method is to design session verification and the like.
Related codes:
/** * 判断是否是AJAX提交 * @return bool */ function is_ajax() { if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') return true; else return false; }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to judge whether it is an ajax submission in PHP native. For more information, please follow other related articles on the PHP Chinese website!