Tips to secure AJAX Request With PHP

Security is very primary concern of any web admin and developers, now days we are using a lot of AJAX functionality to access data and set data, so we need to more secure Ajax request on website. We can use some technics on MySQL side as well as PHP side. In This tutorial we will learn best security tips to secure AJAX calls from website hackers.

Below are some methods and steps which need to be taken to secure your jQuery AJAX calls:

MySQL side

We can apply following tips to secure Ajax request with php.

  • We can use mysqli_real_escape_string function to set data in query.

PHP Server-Side

We can apply following tips and tricks to secure Ajax on server-side with PHP.

  • We can use htmlspecialchars function to echo HTML string.
  • validate inputs
  • disabled global variable

jQuery AJAX call

We can do following things on Ajax call to secure Ajax request.

Step 1: We need to check request is Ajax call.

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

Step 2: We can create a session for client and append with each ajax request.

token = md5(rand(9900,1111));
$_SESSION['token'] = $token;

Step 3: We need to send token with each Ajax request.

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: {token:''},
  success: function(response)
  {
    //do further
  }
});

I hopes its help you to secure your AJAX call.