Use PHP to determine if it is an AJAX request

Source: Internet
Author: User
For some API interfaces, it usually checks whether the request is an AJAX request, which can improve the security to a certain extent.

For some API interfaces, it usually checks whether the request is an AJAX request, which can improve the security to a certain extent.

First, how to differentiate the front-end when using jQuery:

When jQuery sends an ajax request, a message named X-Requested-With is added to the request header. the message content is XMLHttpRequest.

You can use $ _ SERVER ["HTTP_X_REQUESTED_WITH"] on the backend to obtain the data. (Note: The dashes are replaced by underscores, which are case-insensitive)

Therefore, we can determine whether the request is an ajax request:

 
 
  1. // Php determines if it is an ajax request
  2. if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ 
  3. // Ajax request processing method
  4. }else{ 
  5. // Normal request handling method
  6. };

When using native JavaScript to send an ajax request, we can also add information to the header to facilitate the differentiation of backend students. the method is as follows:

 
 
  1. var xmlhttp=new XMLHttpRequest(); 
  2. xmlhttp.open("GET","test.php",true); 
  3. xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest"); 
  4. xmlhttp.send();

Here we also add the X_REQUESTED_WITH information to the header, which is consistent with that of jQuery. Of course, you can also change it to other information for differentiation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.