How PHP determines if it is an AJAX request

Source: Internet
Author: User
For the sake of the security of the program, in some cases we will need to detect whether a request is an AJAX request, how to judge it?

This article will briefly share the experience.

1. When using native JavaScript to make AJAX requests, we can add information to the request header to make it easier for the backend PHP program to differentiate, as follows:

var xmlhttp=new xmlhttprequest (); Xmlhttp.open ("GET", "test.php", true); Xmlhttp.setrequestheader ("X-requested-with", "XMLHttpRequest"); Xmlhttp.send ();

Here we add x_requested_with information to the head, the value is XMLHttpRequest, of course, the value here can be arbitrarily set, such as: www.phpernote.com. This can be written on the receiving side of the PHP program:

!--? php//PHP to determine if the AJAX request if (Isset ($_server[& #39; http_x_requested_with& #39;]) &&strtolower ($_server[& #39; http_x_requested_with& #39;]) ==& #39; xmlhttprequest& #39;) {//Ajax request Processing mode}else{//Normal request processing}  

2. Now the more popular JS framework jquery is considered quite well, when JQuery makes an AJAX request, it adds a name called X-r to the request header. Equested-with information, the information content is: XMLHttpRequest, so the back-end PHP can also be used as the code to judge.

Note: If your jquery request is to open a Web page through an iframe, then the Http_x_requested_with parameter is not passed, meaning you have no way of judging the type of the request.

  • 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.