How to detect AJAX request in PHP
Snippet
Firstly, there is no reliable way to know that the request was made via Ajax. You should never trust data coming from the client.
But you can use headers to detect the ajax request. The HTTP_X_REQUESTED_WITH
header is sent by all recent browsers that support AJAX requests.
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
// this is ajax request, do something
}
From PHP 7 with null coalescing operator it will be shorter:
$isAjax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );