Reputation: 139
I've found this stack overflow page with the PHP function below and it works perfectly but I don't have enough user reputation to comment on that page and ask for help so that's why I created a new question about this.
Let's say I use the function in my code below to generate a 6 or 8 character key how much chance do I have that this function will generate the same key twice? Is it once every thousand / million / billion times ?
Thank you..
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;
}
Upvotes: 0
Views: 659
Reputation: 16953
If all you need is a unique ID, you can just use the uniqid()
function.
Upvotes: 2