Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying XMLHttpRequest in php

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/[email protected] to make the php site eat their email and run a thousand requests on the page? Thanks in advance

like image 542
DrLime2k10 Avatar asked Dec 18 '11 17:12

DrLime2k10


2 Answers

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.

like image 175
Sweam Avatar answered Nov 01 '22 11:11

Sweam


That is fundamentally impossible.

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

like image 20
SLaks Avatar answered Nov 01 '22 12:11

SLaks