Leo
Leo

Reputation: 1768

easiest way to generate an unique and random key

the question is not 'how to' generate such a key. There are tons of answers. Some are too simple like a timestamp but others are not unique enough like some chars with rand().

What I thougth is, why not combine both? If I take the timestamp in seconds or milliseconds and add random chars (but no numbers) in between, wouldn't that result a random and unique string?

The question is not specific to one programming language but to give you some code I made it in php:

$token = (string) preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', microtime());
$l = strlen($token);
$c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($i = 0; $i < $l; $i++){
    $token = substr_replace($token, $c[rand(0, 51)], rand(0, $l+$i), 0);
}

echo $token;

I'm realy looking forward for some randomness-pro's answer!

Thanks ;) Lenny

Upvotes: 1

Views: 479

Answers (1)

Rob S.
Rob S.

Reputation: 1146

I prefer to generate a GUID. Here is some code that will do that for you.

 function getGUID(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
            return $uuid;
        }
    }

        $GUID = getGUID();
        echo $GUID;

Here is my source. http://guid.us/GUID/PHP

Upvotes: 2

Related Questions