5 Tips to Secure AJAX PHP Call

Now a days, we always use Ajax for getting data without refreshing a page in our project. Ajax is a good approach to load data smoothly on page without reloading.   

Simply Getting ajax request response is not secure way. So, in this tutorial we will see how to secure ajax request or how to make secure Ajax call

Step 1.  First of all check request is AJAX request or not.

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
echo "AJAX request";
}
else{
echo "Not AJAX";
}

Step 2. Check Referer : Give response only when AJAX request is from your own url

if(!empty($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="www.mywebiste.com/ajaxurl") 
{
//AJAX Request from own server
}

Step 3. Use Post Method in AJAX

Always Use Post method while sending request and check $_POST variable before giving response  

Step 4. Use Token While Sending Ajax Call

  session_start();   
$token = md5(rand(10000,99999));
$_SESSION['token'] = $token; //store it as session variable

Step 5. Use Two way encryption

Send encrypt data and before giving result check request with decrypt.

Learn how to use two way encryption in PHP.

Simple Two Way Encryption in PHP


Leave a Comment