2

Detect Ajax Request-Php And Frameworks

Detecting ajax request in PHP is not a very tough task and there are many ways to detect it using client side code, for example, if you send a flag/sign i.e. http://example.com?isAjax=1 with the request to the server and check it on the server side if( isset( $_GET['isAjax'] ) && $_GET['isAjax'] ) if that variable exists and contains that variable then you can make sure that the request is made using ajax. You can also set a custom header using setRequestHeader method and can check on the server side if that header is set or not and this the proper way to do this and this technic is being used by developers. An example is given below

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handler;
xhr.open("GET", "your_url");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();

In the given example xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); is setting a custom header to the request and you can retrieve this header from the $_SERVER array using $_SERVER['HTTP_X_REQUESTED_WITH'] for example, you can check this in PHP like

if(isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest')
{
    // This is an ajax request
}

You can also make function or class method like

function isAjax(){
    return isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

//You can use it as a function
if( isAjax() )
{
    // This is an ajax request
}

Well, this is very simple and this is the most preferable technique that developers use. In this case you don’t have to use HTTP_X_REQUESTED_WITH same header, you can use your own header like xhr.setRequestHeader('X-Ajax-request', 'XMLHttpRequest') and in PHP you can use $_SERVER['HTTP_X_AJAX_REQUEST'] and this will work but you should not use your own, why ?

It’s because the X-Requested-With header is not a HTTP standard header but it’s likely a de facto standard, which means this header is being used by developers and many JavaScript libraries like jQuery and Dojo uses this custom header, They send this header with every ajax request and also many PHP frameworks like Symphony, Laravel and CodeIgniter uses this technic to check the request.

Non-standard header fields were conventionally marked by prefixing the field name with X- . However, this convention became deprecated in June 2012 due to the inconveniences it caused when non-standard headers then became standard. For example, X-Gzip and Gzip are now both supported headers for compressed HTTP requests and responses. Read more

For example, Symphony’s HttpFoundation component contains following public method in the Request class

public function isXmlHttpRequest()
{
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}

In this case, Laravel also uses this same technic, because it’s depended on Symphony components and in the the namespace Illuminate\Http the Request class is something like this

class Request extends \Symfony\Component\HttpFoundation\Request {
    //...

    /**
     * Determine if the request is the result of an AJAX call.
     * 
     * @return bool
     */
    public function ajax()
    {
        return $this->isXmlHttpRequest();
    }
}

Same thing for CodeIgniter too, in the system/core/Input.php file there is a method is_ajax_request() in the Input class

class CI_Input {
    // ...
    /**
     * Is ajax Request?
     *
     * Test to see if a request contains the HTTP_X_REQUESTED_WITH header
     *
     * @return 	boolean
     */
    public function is_ajax_request()
    {
        return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest');
    }
}

So, we should use the same header that is being used by developer community to keep our code working with any framework or third party libraries. Now, if we use jQuery or other library which automatically sets the header then we don’t have to worry about it but in case we use our own JavaScript library or vanilla JavaScript code then we have to set the custom header by ourselves to develop a site/application using these PHP frameworks. Also, if we don’t use these frameworks and instead, if we use plain PHP code written by ourselves from the scratch, then we can easily adopt this technic by writing the isAjax() function (given above) in our PHP file/class and in our JavaScript code we can set the custom header using setRequestHeader() function.

According to the RFC-6648 the X- is deprecated and both X-REQUESTED-WITH and REQUESTED-WITH are now supported headers but to maintain the backward compatibility we should use X-REQUESTED-WITH header in our code like xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'), otherwise our vanilla Javascript code may not work with many frameworks.

Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]