Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the request is an AJAX request with PHP

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?

like image 384
BackSlash Avatar asked Aug 15 '13 19:08

BackSlash


People also ask

Which indicates whether or not the specified HTTP request is an AJAX request?

The X-Requested-With header returns a string that indicates whether it's an Ajax request or not. An Ajax request will have this header set to XMLHttpRequest.

How do I know if AJAX is working?

ajax() : $. ajax({ type: 'POST', url: 'page. php', data: stuff, success: function( data ) { }, error: function(xhr, status, error) { // check status && error }, dataType: 'text' });

Are AJAX requests HTTP requests?

An AJAX request is a request made by an AJAX application. Typically, it is an HTTP request made by (browser-resident) Javascript that uses XML to encode the request data and/or response data.


1 Answers

Here is the tutorial of achieving the result.

Example:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {       exit;     } continue; 

This checks if the HTTP_X_REQUESTED_WITH parameter is not empty and if it's equal to xmlhttprequest, then it will exit from the script.

like image 157
Volodymyr Avatar answered Oct 16 '22 15:10

Volodymyr