How to find out if a request came via AJAX

To distinguish between direct and AJAX requests, just check the value of the global variable $_SERVER ['HTTP_X_REQUESTED_WITH'].

<?php
if (@$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
	// Handling an AJAX request
}
PHP

Using this method for security purposes does not make any sense since any headers can be passed to the server, for example via cURL.

19.12.2016, updated 23.02.2021
60

Comments

to add a comment.

Other publications

Regular Expression Shortcodes
Often on sites, it becomes necessary to insert dynamic information blocks into the texts of pages - banners, phones...
25
0
Checking data with regular expressions
A collection of regular expressions with examples in PHP for validating data from form fields.
49
0
Automatic setting of the user's time zone
date_default_timezone_set sets the default timezone used by all date / time functions.
113
0
Serialize function, possible problems
The serialize () function returns a string representation of any value (array, object, etc.). Using serialize on an...
32
0
Session lifetime in PHP
By default, in php, the session lifetime is only 24 minutes, and cookies are saved until the browser is closed, such parameters are set on many hosting services.
152
0
Working with PHP arrays - creating, filling, deleting
Basic examples of working with PHP arrays. Creation, filling, extraction and removal of values.
107
0