PHP 表单令牌的使用和处理 [英] PHP form token usage and handling

查看:16
本文介绍了PHP 表单令牌的使用和处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名使用 PHP 编写登录脚本的初学者.这是我到目前为止的表单令牌声明:

I'm a beginner working on a login script in PHP. This is the form token statement that I have so far:

$_SESSION["form_token"] = md5(rand(time (), true)) ;

该语句是在用户表示他/她想要登录后立即发出的.

The statement is issued just after the user indicates that he/she wants to login.

我有限的理解是令牌的目的是在唯一的时间点识别唯一的用户并伪装形式令牌信息.

My limited understanding is that the tokens purpose is to identify a unique user at a unique point in time and to disguise the form token information.

然后一切都变得模糊了.这是我的 3 个未解决的问题:

Then everything becomes fuzzy. Here are my 3 open questions:

  1. 出于安全目的检查"表单令牌的最佳时间是什么时候?

  1. When is the best time to "check" the form token for security purposes?

我该如何检查?

我什么时候销毁"表单标记?(IOW,表单令牌会保持活动"状态,直到用户注销?

When, if ever, do I "destroy" the form token? (IOW, would the form token stay "active" until the user logs out?

推荐答案

没有必要做你正在尝试的事情.当您在 PHP 中使用 session_start() 启动会话时,已经为您生成了唯一的 SESSIONID.你不应该把它放在表格上.默认情况下,它是通过 cookie 处理的.也不需要检查 SESSIONID,它会再次为您处理.

There is no need to do what you are attempting. When you start a session in PHP with session_start() a unique SESSIONID is already generated for you. You should not be putting this on the form. It is handled via cookies by default. There is also no need to check the SESSIONID either, that again is handled for you.

您负责对用户进行身份验证并存储他们经过身份验证的身份(例如,会话中的 $_SESSION['user_id'] = $userId.如果用户退出,您可以使用 session_destroy 销毁他们的会话.

You are responsible for authenticating the user and storing their authenticated identity (e.g. $_SESSION['user_id'] = $userId in the SESSION. If a user logs out you destroy their session with session_destroy.

您应该确保 session_start() 是您网站中所有页面的首要事情之一.

You should ensure session_start() is one of the first things for all pages in your site.

这是一个基本示例:

<?php
session_start(); // starts new or resumes existing session
session_regenerate_id(true); // regenerates SESSIONID to prevent hijacking

function login($username, $password)
{
    $user = new User();
    if ($user->login($username, $password)) {
        $_SESSION['user_id'] = $user->getId();
        return true;
    }
    return false;
}

function logout()
{
    session_destroy();
}

function isLoggedIn()
{
    return isset($_SESSION['user_id']);
}

function generateFormHash($salt)
{
    $hash = md5(mt_rand(1,1000000) . $salt);
    $_SESSION['csrf_hash'] = $hash
    return $hash;
}

function isValidFormHash($hash)
{
    return $_SESSION['csrf_hash'] === $hash;
}

我误解了最初的问题.我添加了上面生成和验证表单哈希的相关方法;

I misunderstood the original question. I added the relevant methods above for generating and validating form hashes;

请查看以下资源:

这篇关于PHP 表单令牌的使用和处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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