5

I am sending data to a PHP site using the following code:

if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp= new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
          xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.open("GET","addEmail.php?email="+escape(email),true);
      xmlhttp.send();
      xmlhttp.close;

Is there any way of making sure that the addEmail.php is being run through the XMLHttpRequest so people cant simply go to www.domain.com/addEmail.php?email=some@thing.com to make the php site eat their email and run a thousand requests on the page? Thanks in advance

Eje
  • 354
  • 4
  • 8
DrLime2k10
  • 276
  • 1
  • 2
  • 14
  • http://stackoverflow.com/questions/1953954/detecting-ajax-in-php-and-making-sure-request-was-from-my-own-website – Eric Pigeon Dec 18 '11 at 18:09

3 Answers3

21

The users is always able to access the php script directly, but you can protect is a bit more by adding this check to the php script:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
  //CODE HERE
}

Additionally, like Eugen Rieck mentioned, you could send a token.

Sweam
  • 422
  • 4
  • 10
  • Thanks!, that was probably what I was looking for.. sidequestion, Why do you have the 3x = checking whether its equal to 'xmlhttprequest' ? – DrLime2k10 Dec 18 '11 at 18:17
  • 1
    === checks if they are of the same type. It's probably sufficient to use two. – Sweam Dec 18 '11 at 18:28
2

That is fundamentally impossible.

You need to limit the number of requests per IP address on the server.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

The standard way to do this, is to send some sort of (time dependent) token with the page that contains the AJAX code, then send the token together with the AJAX call. Users who directly use the AJAX URL will not know the current token value.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92