[英]CSRF Token validation when processing
I have seen questions on this topic but cant seem to find a solution. 我已经看到有关此主题的问题,但似乎找不到解决方案。 On my index page, at the top I am simply doing
在索引页面的顶部,我只是在做
<?php
session_start();
function generate_secure_token($length = 16) {
return bin2hex(openssl_random_pseudo_bytes($length));
}
$_SESSION['token'] = generate_secure_token();
$token = $_SESSION['token'];
?>
I then set $token
as a hidden field within my form. 然后,我将
$token
设置$token
表单中的隐藏字段。 My question is relating to the processing of the form. 我的问题与表格的处理有关。 At the moment I have
此刻我有
if ( empty( $_POST[ 'csrf_token' ] ) )
{
$errors['token'] = 'Something went wrong';
}
So it simply checks that a token exists. 因此,它仅检查令牌是否存在。 Is this enough?
这够了吗? I have seen other examples recreating the token and then comparing it with the session token, but not sure if I need this?
我看到了其他示例重新创建令牌,然后将其与会话令牌进行比较,但不确定是否需要此令牌?
Any advice on how I can validate this properly appreciated. 关于如何验证这一点的任何建议都应受到赞赏。
Thanks 谢谢
You should compare the given token to your session token to be sure that the introduced token is valid: 您应该将给定令牌与会话令牌进行比较,以确保引入的令牌有效:
if ( empty( $_POST[ 'csrf_token' ] ) ||
$_POST[ 'csrf_token' ] != $_SESSION['token'])
{
$errors['token'] = 'Something went wrong';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.