php - 为每个现有用户生成唯一代码时出现 PHP 错误
问题描述
我必须为我的数据库中的每个用户生成唯一的哈希码。我使用 2 个功能:
这是一个在没有此键的情况下调用所有用户的查询:
public function actionGenerate() {
$users = User::find()->where('forget_code IS NULL ')->all();
if($users and count($users) > 0) {
foreach ($users as $user) {
$code=$this->getForgetToken((int)$user->id); // here give me the error
$user->forget_code = $code;
$user->update(false);
}
}
}
这是其他两个功能:
function getForgetToken($id,$length=32) {
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
for($i=0;$i<$length;$i++) {
$token .= $codeAlphabet[$this->crypto_rand_secure($id,0,strlen($codeAlphabet))];
}
return $token;
}
function crypto_rand_secure($id,$min, $max) {
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $id + $min + $rnd;
}
解决方案
您传递的$max
1 太多了,因为strlen()
1 在数组索引之前(基于 0)。从 strlen 中减去 1
$this->crypto_rand_secure($id, 0, strlen($codeAlphabet) - 1)
推荐阅读
- python - 单击按钮时显示图像 Python GUI
- python - Python numpy:索引20超出轴0的范围,大小为20?
- swagger - 在 WebDeploy 之后无法访问 Swagger UI
- session - 在 NextJS getServerSideProps 中使用 Bearer 令牌装饰 api 请求
- rust - 在 Rust 中修改单个字节
- mysql - 检查与您的 MySQL 版本相对应的手册,以在第 1 行的“限制 100”附近使用正确的语法
- c# - C# Unity 不能将浮点类型隐式转换为 int
- reactjs - 我无法使用 npm start 命令运行反应应用程序
- jquery - 如何使用 jQuery 获取类的下一个实例
- reactjs - 一次只选择一个计划 React State Hook