PHP and AJAX security question

30,151

Solution 1

Concluded Answer after googling a lot !

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = {
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

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

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); //most of people forget this while copy pasting code ;)
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else {
      header('Location: http://yourdomain.com');
    }
  }
  else {
    header('Location: http://yourdomain.com');
  }
}
else {
  header('Location: http://yourdomain.com');
}

NOTE: SORRY FOR NESTED IF..ELSE, BUT IT INCREASES UNDERSTANDABILITY. YOU CAN SIMPLIFY ALL THREE IN ONE IF ELSE. 85% Security Enhanced !

Solution 2

Quoting Eran Galperin from a similar discussion

As others have said, Ajax request can be emulated be creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use:

if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
 //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

Please take this answer by Jeremy Ruten also into account:

There is no way of guaranteeing that they're accessing it through AJAX. Both direct access and AJAX access come from the client, so it can easily be faked.

Why do you want to do this anyways?

If it's because the PHP code isn't very secure, make the PHP code more secure. (For example, if your AJAX passes the user id to the PHP file, write code in the PHP file to make sure that is the correct user id.)

More clever thoughts in the discussion linked above.

Solution 3

some way are required for secure connection ajax and php . you can use

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

dont forget to secure php file because with cURL can spoof headers .

Solution 4

you could also block hotlinking if you are worried that others might access your content without your approval

see: http://www.htmlbasix.com/disablehotlinking.shtml

Solution 5

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

Share:
30,151

Related videos on Youtube

carter663
Author by

carter663

Updated on July 09, 2022

Comments

  • carter663
    carter663 almost 2 years

    I am currently building a web app in which PHP files are loaded into a main file using jQuery's $.ajax function. However, the PHP files are obviously still accessible outside of the app, by just typing the files name in the address bar.

    So my question is what would be the best way to make it so that the PHP file being 'ajaxed' in knows that it is contained in the correct page and will function correctly, but if it is accessed in any other way (even if someone were to make they're own website and AJAX in my PHP file) then the file should say "access denied" or something.

    Thanks in advance

  • rook
    rook almost 14 years
    So how exactly is someone supposed to access this page with an XMLHttpRequest? Are you aware of the same origin policy?
  • middus
    middus almost 14 years
    I am aware of the same origin policy. The check for XMLHttpRequest can be made in order to find out whether the script hast been called via AJAX (i.e. your own script) or whether someone pointed his browser to this location. Calling the script from the Firbug console of your own site is a different story, though.
  • arlg
    arlg over 9 years
    The $token = md5(rand(1000,9999)); line makes my local PHP 20 seconds to reload the page.
  • dartanian300
    dartanian300 about 9 years
    How would this prevent against someone sending a call over the console? Would that have the same HTTP_REFERER?
  • zeuf
    zeuf over 8 years
    In this case, the token is useless as the JS script (Step-2) is readable by the user.
  • Hardik Thaker
    Hardik Thaker over 8 years
    @zeuf: token is generated "everytime (each request)" on page load by the server. So it doesn't matter.
  • Hardik Thaker
    Hardik Thaker over 8 years
    @dartanian300: Any one can forge the http call. HTTP_REFERER can be modified. For better security you can add user session check before processing anything.
  • Nick Marden
    Nick Marden about 8 years
    @HardikThaker @zeuf If you are concerned about the token being in the javascript - you can utilise a salt on the server side. For example: $randomNumber = rand(1000, 9999); $browserToken = hash("sha256", $randomNumber); $saltValue = "abc123456"; $serverToken = $browserToken . $saltValue; $serverToken = hash("sha256", $serverToken); $_SESSION["token"] = $serverToken; And then when verifying you simply recreate the serverToken and verify it matches.