How to check if a Request is AJAX call with PHP

It is useful to prevent direct access of AJAX calls (from browser address bar).

A solution could be the following simple function check_is_ajax():

/**
 * Check if request is an AJAX call
 *
 * @param string $script script path
 */
function check_is_ajax($script) {
        $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
        if(!$isAjax) {
                trigger_error('Access denied - not an AJAX request...' . ' (' . $script . ')', E_USER_ERROR);
        }
}

Example

Put the following at the top of your AJAX call:

check_is_ajax(__FILE__); // prevent direct access

References

From PHP manual

Your comments are welcome!


Don't miss any updates!

Subscribe to our free NewsLetter