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'] ?? '' );
Similar Snippets
- Check if two arrays values are equal
- Validate URL
- Check if string starts with certain characters
- How to check the connection to MySQL
- Check if user agent is bot
- Check if a string is serialized
- Check if all values in array are equal
- Case-Insensitive in_array
- Extract all bit flags
- Check if bit flag is set