Home >Backend Development >PHP Tutorial >PHP determines whether a request is an AJAX request or a normal request_PHP Tutorial
In a PHP program, how to determine whether a web page request is an ajax request or a normal request? We often have such a problem when working on projects. After directly entering the address submitted by my ajax into the browser, the browser can directly request the data and print the data to the page. From the perspective of procedural rigor and safety, I think this is very bad.
However, due to my limited level, this problem was not solved by me until today. I hereby leave the article for those who need it to learn from.
First let’s talk about the principle: when sending an ajax request, we can create custom header information through the XMLHttpRequest object. If you are using the native ajax method, that is, without using jquery or other js framework packaging ajax method, then the code is as follows:
xmlHttpRequest.setRequestHeader("request_type","ajax");
In addition, through the $.ajax() method wrapped by jquery, we can easily create our custom header information before sending the ajax request. The example is as follows:
$.ajax({ type:"GET", url:base_url + 'php_check_ajax_request/get_user_list.html', beforeSend:function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("request_type","ajax"); }, success:function(data){ $("#user_list").html(data); $tip.hide(); $button.attr('disabled',true); } });
There is a sentence in the above code:
XMLHttpRequest.setRequestHeader(“request_type”,”ajax”);
This line of code creates a custom variable "request_type" in the header information. This variable receives variables in php as follows:
$_SERVER['HTTP_REQUEST_TYPE']
So for the question raised in this article, we can judge the request sent by the user in the following way.
<?php if (isset($_SERVER['HTTP_REQUEST_TYPE']) && $_SERVER['HTTP_REQUEST_TYPE'] == "ajax"){ //ajax提交 }else{ //非ajax提交 }
It should be noted that the variable value of "request_type" is customized by us. You can also customize it at will, such as "test", "is_ajax", etc.