I would like to check server-side if a request to my php page is an ajax request or not.
I saw two ways to do this:
First way: sending a GET parameter in the request which tells the page that this is an AJAX request (=mypage.php?ajax)
mypage.php:
if(isset($_GET['ajax'])) {
//this is an ajax request, process data here.
}
Second way: set a header to the xmlHttpRequest:
client-side js:
xmlHttpRequestObject.open(“GET”,url,true);
xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
mypage.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
//request is ajax
}
The fact is, those two ways of doing it can easily be hacked, so it's not secure to check if i get an AJAX request like this.
How can i check if i'm receiving an AJAX request?