mysqli_ list php | debian wheezy no mysql log | debian 6 vs 7 | detecting browser with javascript
 


 

How to check if a Request is an 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

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

More tips