简体   繁体   English

PHP - 如何在同一页面的多个forms中使用csrf token

[英]PHP - How to use csrf token in multiple forms on the same page

I have 2 forms on the same page.我在同一页上有 2 forms。 I want to use the csrf token in both forms. when I try to use it, it regenerates the csrf token on form submission.我想在两个 forms 中都使用 csrf 令牌。当我尝试使用它时,它会在提交表单时重新生成 csrf 令牌。

How can I solve this?我该如何解决这个问题?

<?php

function csrf_token() {
    return bin2hex(random_bytes(35));
}

function create_csrf_token() {
    $token = csrf_token();
    $_SESSION['csrf_token'] = $token;
    $_SESSION['csrf_token_time'] = time();
    return $token;
}

function csrf_token_tag() {
    $token = create_csrf_token();
    return '<input type="hidden" name="csrf_token" value="' . $token . '">';
}

$csrf_token = csrf_token_tag();
?>

<form action="" method="post">
    ...
    <?= $csrf_token; ?>
</form>

<form action="" method="post">
    ...
    <?= $csrf_token; ?>
</form>

When you refresh the page, the function created_csrf_token gets fired again, changing the CSRF token.刷新页面时,function created_csrf_token会再次触发,更改 CSRF 令牌。

As Lawrence has commented, you can scope it.正如劳伦斯评论的那样,您可以拨打 scope。 Eg例如

<?php

function csrf_token() {
    return bin2hex(random_bytes(35));
}

function create_csrf_token() {
    if (isset($_SESSION['csrf_token'])) {
        return $_SESSION['csrf_token'];
    }
    $token = csrf_token();
    $_SESSION['csrf_token'] = $token;
    $_SESSION['csrf_token_time'] = time();
    return $token;
}

function csrf_token_tag() {
    $token = create_csrf_token();
    return '<input type="hidden" name="csrf_token" value="' . $token . '">';
}

$csrf_token = csrf_token_tag();
?>

<form action="" method="post">
    ...
    <?= $csrf_token; ?>
</form>

<form action="" method="post">
    ...
    <?= $csrf_token; ?>
</form>

Adding an isset into the create_csrf_token will check if the CSRF token is set, and return the existing, rather than create a new one.create_csrf_token中添加一个 isset 将检查是否设置了 CSRF 令牌,并返回现有令牌,而不是创建一个新令牌。

You probably want to add some logic though, to create a new CSRF token after around 5 minutes.不过,您可能想要添加一些逻辑,以便在大约 5 分钟后创建一个新的 CSRF 令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM