如何防止在 PHP 中多次单击时提交多个表单 [英] How to prevent multiple form submission on multiple clicks in PHP

查看:29
本文介绍了如何防止在 PHP 中多次单击时提交多个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP如何防止多次点击提交多个表单

解决方案

使用每次显示表单时生成的唯一令牌,该令牌只能使用一次;防止 CSRF重放 攻击.一个小例子:

 1);}别的{$_SESSION['tokens'][$token] = 1;}返回 $token;}/*** 检查令牌是否有效.从有效令牌列表中删除它* @param string $token 令牌* @return 布尔值*/函数 isTokenValid($token){if(!empty($_SESSION['tokens'][$token])){未设置($_SESSION['tokens'][$token]);返回真;}返回假;}//检查表单是否已发送$postedToken = filter_input(INPUT_POST, 'token');if(!empty($postedToken)){if(isTokenValid($postedToken)){//处理表单}别的{//对错误做一些事情}}//获取我们正在显示的表单的标记$token = getToken();?><form method="post"><字段集><input type="hidden" name="token" value="<?php echo $token;?"/><!-- 添加表单内容--></fieldset></表单>

将它与重定向结合起来,这样您就可以保持完美的前后行为.有关重定向的更多信息,请参阅 POST/redirect/GET 模式.>

How to prevent multiple form submission on multiple clicks in PHP

解决方案

Use a unique token generated each time you display a form and which can be used only one time; it is also usefull to prevent CSRF and replay attacks. A little example :

<?php
session_start();

/**
 * Creates a token usable in a form
 * @return string
 */
function getToken(){
  $token = sha1(mt_rand());
  if(!isset($_SESSION['tokens'])){
    $_SESSION['tokens'] = array($token => 1);
  }
  else{
    $_SESSION['tokens'][$token] = 1;
  }
  return $token;
}

/**
 * Check if a token is valid. Removes it from the valid tokens list
 * @param string $token The token
 * @return bool
 */
function isTokenValid($token){
  if(!empty($_SESSION['tokens'][$token])){
    unset($_SESSION['tokens'][$token]);
    return true;
  }
  return false;
}

// Check if a form has been sent
$postedToken = filter_input(INPUT_POST, 'token');
if(!empty($postedToken)){
  if(isTokenValid($postedToken)){
    // Process form
  }
  else{
    // Do something about the error
  }
}

// Get a token for the form we're displaying
$token = getToken();
?>
<form method="post">
  <fieldset>
    <input type="hidden" name="token" value="<?php echo $token;?>"/>
    <!-- Add form content -->
  </fieldset>
</form>

Combine it with a redirect so you keep a perfect backward and forward behavior. See the POST / redirect / GET pattern for more information about the redirect.

这篇关于如何防止在 PHP 中多次单击时提交多个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆