为什么我们提交表单时会生成一个新的token [英] Why is a new token generated when we submit the form

查看:79
本文介绍了为什么我们提交表单时会生成一个新的token的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力理解 关于 SO 的答案.这是一种防止表单被处理两次的解决方案(如果有人连续两次点击提交"按钮).

I'm struggling to understand an answer on SO. It's a solution which prevents the form from being processed twice (if someone clicks "submit" button twice in a row).

它生成一个唯一的令牌并将其存储在表单中.所以如果提交按钮被点击两次,它将忽略重复提交.

It generates a unique token and stores it in the form. So if the submit button is clicked twice it will ignore the duplicate submission.

代码是

    // form.php
    <?php
        // obviously this can be anything you want, as long as it is unique
        $_SESSION['token'] = md5(session_id() . time());
    ?>
    <form action="foo.php" method="post">
        <input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
        <input type="text" name="bar" />
        <input type="submit" value="Save" />
    </form>

    // foo.php
    if (isset($_SESSION['token']))
    {
        if (isset($_POST['token']))
        {
            if ($_POST['token'] != $_SESSION['token'])
            {
                // double submit
            }
        }
    }

每个人都同意这是正确的解决方案,但我不明白为什么 $_SESSION['token'] 会在我们第二次单击提交按钮时发生变化.

Everyone agrees that it's the right solution, but I don't understand why the $_SESSION['token'] changes the second time we click the submit button.

感谢您的帮助

推荐答案

根据@FunkFortyNiner 提供的链接,我想我想通了,希望我理解正确.

Based on the supplied link by @FunkFortyNiner I think I figured it out, hopefully I understood this correctly.

会发生什么:如果我们单击提交按钮两次,$_POST 令牌将保持不变,但 $_SESSION 令牌(在标题中定义)将更改..

What happens: If we click the submit button twice the $_POST token will remain the same but the $_SESSION token (defined in the header) will change..

来自链接:此处

表单令牌的设置具有二级安全功能.因为PHP 会话存储在服务器端,可以根据POSTed 表单令牌和存储在服务器上的表单令牌.这确保了被 POST 的表单实际上是正确的表单而不是第三方表格.这意味着它是我们的表格.支票是一个简单的字符串比较.

The setting of a form token has a secondary security function. Because PHP sessions are stored server side, a check can be made against the POSTed form token and the form token which is stored on the server. This ensures that the form being POSTed is, in fact, the correct form and not a third party form. This means it is our form. The check is a simple string comparison.

当我们点击提交两次时,PHP 将重新生成令牌两次(服务器端),但表单本身保持不变(客户端没有重新生成 HTML 标记形式).

When we click submit twice PHP will regenerate the token twice (server side), but the form itself remains the same (client side hasn't regenerated the HTML markup of the form).

换句话说,PHP 会在每次提交"请求时重新生成令牌,但您的浏览器不会重新生成包含该令牌的表单.

In other words PHP regenerates the token with each "submit" request, but your browser doesn't regenerate the form that contains the token.

这篇关于为什么我们提交表单时会生成一个新的token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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