我在下面的PHP函数中找到了this stack overflow page,它工作得很好,但是我没有足够的用户信誉在页面上发表评论并寻求帮助,所以这就是为什么我会对此提出一个新的问题。
假设我在下面的代码中使用这个函数来生成一个6或8个字符键,那么这个函数产生两次相同的键的可能性有多大呢?是每千亿次一次吗?
谢谢。。
function crypto_rand_secure($min, $max) {
$range = $max - $min;
if ($range < 0) return $min; // not so random...
$log = 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 $min + $rnd;
}
function getToken($length){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
for($i=0;$i<$length;$i++){
$token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
}
return $token;
}发布于 2014-09-05 12:04:09
如果您只需要一个唯一的ID,则只需使用uniqid()函数即可。
https://stackoverflow.com/questions/25685448
复制相似问题