Generate a unique string in PHP
PHP December 13th, 2007Here is an example of generating a unique string in PHP very useful in some cases especially when you work with large amounts of rows in a db table and you want unique and "hard to find" keys for every row.
My usual method to do this was using the strtotime() function, with "now" as the argument and to the result I was applying the md5() to get a random unique id. The result is fine until you run the script more then 1 time in a second when you get the same string. Here is the new way I do to get a real unique ID not depending on time:
CODE:
-
function unique_id(){
-
$better_token = md5(uniqid(rand(), true));
-
$unique_code = substr($better_token, 16);
-
$uniqueid = $unique_code;
-
return $uniqueid;
-
}
-
-
$id = unique_id();
-
echo $id;
This time I use the rand() and uniqid() functions.
November 4th, 2009 at 4:34 pm
This is what I looking for, thanks.
June 20th, 2010 at 4:33 pm
nice tutorial…
October 10th, 2010 at 2:26 am
hmm, yeah that is really rare, but, still, is there even theoretical possibility of a matching ids, out of say 100k or so?
September 2nd, 2011 at 4:33 pm
md5 will not make an unique number.