Verifying XMLHttpRequest in php

╄→尐↘猪︶ㄣ 提交于 2019-12-22 08:57:48

问题


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


回答1:


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.




回答2:


That is fundamentally impossible.

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




回答3:


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.



来源:https://stackoverflow.com/questions/8553611/verifying-xmlhttprequest-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!