How to check if the request is an AJAX request with PHP How to check if the request is an AJAX request with PHP php php

How to check if the request is an AJAX request with PHP


Here is the tutorial of achieving the result.

Example:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){      exit;    }continue;

This checks if the HTTP_X_REQUESTED_WITH parameter is not empty and if it's equal to xmlhttprequest, then it will exit from the script.


There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.


From PHP 7 with null coalescing operator it will be shorter:

$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );