0

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;
}
Community
  • 1
  • 1
Jack Ottermans
  • 139
  • 3
  • 9
  • That depends on entirely on the min and max values you are using. – Liam Sorsby Sep 05 '14 at 12:03
  • Why re-inventing the wheel when there are several built-in functions to generate unique id's with most probably less collisions... cfr `uniqid()` , `com_create_guid()` , ... – Laurent S. Sep 05 '14 at 12:07

1 Answers1

2

If all you need is a unique ID, you can just use the uniqid() function.

Grim...
  • 16,518
  • 7
  • 45
  • 61