Php determines if it is an ajax request
For the sake of program security, how can we determine whether a request is an AJAX request in some cases? This article briefly shares your experience.
1. When using native JavaScript to send an ajax request, we can add information to the request header to facilitate the differentiation of backend php programs. The method is as follows:
var xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","test.php",true); xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest"); xmlhttp.send();
Here we add the X_REQUESTED_WITH information to the header. The value is XMLHttpRequest. Of course, the value here can be set at will, for example, www.phpernote.com. In this way, you can write in the php program at the receiving end as follows:
<? Php // php determine whether the request is an ajax request if (isset ($ _ SERVER ['HTTP _ X_REQUESTED_WITH ']) & strtolower ($ _ SERVER ['HTTP _ X_REQUESTED_WITH']) = 'xmlhttprequest ') {// ajax request processing method} else {// normal request processing method}
2. currently, jquery, a popular js framework, is fully considered. When jQuery sends an ajax request, it adds a message named X-Requested-With to the Request Header, whose content is XMLHttpRequest, therefore, the backend php can also be judged using the code above.
NOTE: If your jquery request opens a webpage through iframe, The HTTP_X_REQUESTED_WITH parameter will not be passed, that is, you cannot determine the request type.
Articles you may be interested in
- How does php determine whether the current operating system is linux or windows?
- PHP checks whether a request is an AJAX request or a common request.
- Php determines whether the string is full of English, pure Chinese, and a combination of Chinese and English
- PHP checks whether server SSL is enabled, that is, whether HTTPS connections are supported.
- Php methods to determine whether a remote file exists
- Php get_headers determines whether the URL is valid
- How does PHP determine whether a GIF image is a dynamic image (animation)
- How does php determine whether a constant has been defined?