停止从不同域PHP发布数据

Jua*_*uan 8 php forms post

我是PHP的初学者.

我要做的是停止来自其他网页的Post Data.

我遇到的问题是让某人复制我的表格并将其粘贴在他们的网站上.我希望能够阻止Post Data在我的电子邮件表单上运行脚本.

我怎样才能做到这一点?如果我不够清楚,请告诉我.

我的PHP联系表单在一个带有条件语句的页面上运行.即如果数据签出,请提交.

Tom*_*ter 9

您正试图阻止CSRF - 跨站点请求伪造. 杰夫本人有一篇博客文章.

真正的XSRF预防需要三个部分:

  • 隐藏输入字段,以防止有人只是抢夺表单并嵌入它
  • 在生成的表单的epsilon中进行时间检查,否则有人可以生成一次有效表单并使用令牌(取决于强制执行/如何存储)
  • Cookie:这是为了防止恶意服务器伪装成客户端,并执行中间人攻击


T.T*_*dua 8

"accepted answer" has security holes. Instead, you should use more secure methods. A simple example:

Step 1: Disable framing of the page (.php), where the form is generated, in the top add:

header('X-Frame-Options: Deny');
Run Code Online (Sandbox Code Playgroud)

Step 2: (important part ! ): In order to avoid XSS and 3rd party exploits, you should create a expirable validation. For example:

  • ASP.NET builtin forms use dynamic input csrf (example value: gtlkjh29f9ewduh024cfvefb )
  • WordPress builtin forms use dynamic input nonce (example value: 340297658942346 )

So, if you are on a custom platform, which doesn't have built-in temporary token validation methods, then implement your approach. A simple concept:

<?php  
$secret_key      = 'fjd3vkuw#KURefg';  //change this
$encrypted_value = Cryptor::encrypt( time(), $_SERVER['REMOTE_ADDR'] . $secret_key);
?>
<form>
...
...
<input value="<?php echo $encrypted_value;?>" name="temp_random" type="hidden"  />
</form>
Run Code Online (Sandbox Code Playgroud)

(Cryptor code is here )

on submission, check:

if(!empty($_POST)){

   // If REFERRER is empty, or it's NOT YOUR HOST, then STOP it
   if( !isset($_SERVER['HTTP_REFERRER']) || parse_url($_SERVER['HTTP_REFERRER'])['host'] != $_SERVER['HTTP_HOST'] ){
       exit("Not allowed - Unknown host request! ");
   }

   // Now, check if valid
   if (   Cryptor::decrypt(  $_POST['temp_random'], $_SERVER['REMOTE_ADDR'] . $secret_key) < time() - 60* 15 ) {
       exit("Not allowed - invalid attempt! ");
   }

   ...........................................
   ... Now, you can execute your code here ...
   ...........................................

}
Run Code Online (Sandbox Code Playgroud)


And*_*nna 6

$ _SERVER ['HTTP_Referrer']会很好但是不可靠.您可以使用MD5的隐藏表单字段,然后在另一侧检查它.

  • 你不能相信HTTP_Referrer,它很容易被欺骗. (2认同)