为每个现有用户生成唯一代码时出现PHP错误
我必须为数据库中的每个用户生成唯一的哈希代码。我使用两种功能: 下面是一个查询,用于调用不带此键的所有用户:为每个现有用户生成唯一代码时出现PHP错误,php,Php,我必须为数据库中的每个用户生成唯一的哈希代码。我使用两种功能: 下面是一个查询,用于调用不带此键的所有用户: public function actionGenerate() { $users = User::find()->where('forget_code IS NULL ')->all(); if($users and count($users) > 0) { foreach ($users as $user) {
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;
}
函数get遗忘权($id,$length=32){
$token=“”;
$codeAlphabet=“abcdefghijklmnopqrstuvxyz”;
$codeAlphabet.=“abcdefghijklmnopqrstuvwxyz”;
$codeAlphabet.=“0123456789”;
对于($i=0;$icrypto_rand_secure($id,0,strlen($codelphabet))];
}
返回$token;
}
函数加密随机安全($id、$min、$max){
$range=$max-$min;
如果($range<1)返回$min;//不太随机。。。
$log=ceil(log$range,2));
$bytes=(int)($log/8)+1;//字节长度
$bits=(int)$log+1;//以位为单位的长度
$filter=(int)(1$range);
返回$id+$min+$rnd;
}
错误是:
我不明白为什么你传递的
太多了$max
1,因为strlen()
比数组索引早1(基于0)。从strlen中减去1
$this->crypto_rand_secure($id, 0, strlen($codeAlphabet) - 1)
在函数crypto\u rand\u secure
中,您正在向结果中添加$id
,这有时可能会导致表的索引大于表本身。您的表$codelphabet
有62个字符,因此您正在搜索0到61之间的数字,但随后添加$id
,这可能会导致数字大于表本身n 61(例如,$rand
为55,$id
为10,因此函数crypto\u rand\u secure
将重新运行10+0+55,即65(表外)。为什么要编写函数来生成密码,而不是使用openssl\u random\u pseudo\u bytes()
或random\u bytes()
?@user9741470它使用的是openssl\u random\u pseudo\u bytes
,但OP需要random是的,我理解。我更改了它,但这没有帮助…仍然是相同的错误