如何在 PHP 中生成一个在手动重置之前有效的唯一令牌?

How to generate a unique token that is valid until it's manually reset, in PHP?

我需要一些方法来生成可以传递到 MySQL 数据库并存储在那里直到手动重置的唯一令牌。所以它需要是一个随机令牌,将显示给用户,它应该保持有效,但也有一些可以重置它的功能——比如 "reset key" link 自动更新、更改,然后显示新令牌。

我正在尝试这段代码,但每次重新加载页面时它都会刷新:

global $wpdb;
global $user_login;
$token = uniqid();
$hashedtoken = md5($token);
$user = $user_login;

$wpdb->insert('wp_tokens', 
array('user' => $user, 'token' => $hashedtoken),
array('%s','%s')
);
echo $hashedtoken;

很明显我在使用 Wordpress,如果这很重要的话。我什至不确定 PHP 是这里的最佳选择。

编辑: 我的问题被标记为与 this 类似,一些很酷的人通知我需要查询数据库以检查令牌是否存在为用户。但是,不知道如何做这些。谢谢

首先你应该至少使用 sha http://php.net/manual/de/function.sha1.php - 无论你用令牌做什么 - 现在的脚本小子喜欢扫描网络以寻找仍然使用 md5 字符串长度的页面。

快速破解是检查令牌是否已存在于您的数据库中

以下是 PHP 关于使用 uniqid() 生成 "random" 字符串的说法:

Warning This function does not create random nor unpredictable strings. This function must not be used for security purposes. Use a cryptographically secure random function/generator and cryptographically secure hash functions to create unpredictable secure IDs.

非随机字符串的散列仍然不是随机的。

这里是 link 关于在 PHP 中生成随机字符串的两个常见问题:

How to create a random string using PHP?

PHP random string generator

md5(uniqid($your_user_login, true))