首页 > 解决方案 > 为每个现有用户生成唯一代码时出现 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;
}

错误是:在此处输入图像描述 我不明白为什么

标签: php

解决方案


您传递的$max1 太多了,因为strlen()1 在数组索引之前(基于 0)。从 strlen 中减去 1

$this->crypto_rand_secure($id, 0, strlen($codeAlphabet) - 1)

推荐阅读