Unique Alpha numeric generator
Posted
by
AAA
on Stack Overflow
See other posts from Stack Overflow
or by AAA
Published on 2010-12-22T22:08:38Z
Indexed on
2010/12/31
4:53 UTC
Read the original article
Hit count: 295
Hi,
I want to give our users in the database a unique alpha-numeric id. I am using the code below, will this always generate a unique id? Below is the updated version of the code:
old php:
// Generate Guid
function NewGuid() {
$s = strtoupper(md5(uniqid(rand(),true)));
$guidText =
substr($s,0,8) . '-' .
substr($s,8,4) . '-' .
substr($s,12,4). '-' .
substr($s,16,4). '-' .
substr($s,20);
return $guidText;
}
// End Generate Guid
$Guid = NewGuid();
echo $Guid;
echo "<br><br><br>";
New PHP:
// Generate Guid
function NewGuid() {
$s = strtoupper(uniqid("something",true));
$guidText =
substr($s,0,8) . '-' .
substr($s,8,4) . '-' .
substr($s,12,4). '-' .
substr($s,16,4). '-' .
substr($s,20);
return $guidText;
}
// End Generate Guid
$Guid = NewGuid();
echo $Guid;
echo "<br><br><br>";
Will the second (new php) code guarantee 100% uniqueness.
Final code:
PHP
// Generate Guid function NewGuid() { $s = strtoupper(uniqid(rand(),true)); $guidText = substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4). '-' . substr($s,16,4). '-' . substr($s,20); return $guidText; } // End Generate Guid
$Guid = NewGuid(); echo $Guid;
$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
function base_encode($num, $alphabet) { $base_count = strlen($alphabet); $encoded = '';
while ($num >= $base_count) {
$div = $num/$base_count;
$mod = ($num-($base_count*intval($div)));
$encoded = $alphabet[$mod] . $encoded;
$num = intval($div);
}
if ($num) $encoded = $alphabet[$num] . $encoded;
return $encoded;
}
function base_decode($num, $alphabet) { $decoded = 0; $multi = 1;
while (strlen($num) > 0) {
$digit = $num[strlen($num)-1];
$decoded += $multi * strpos($alphabet, $digit);
$multi = $multi * strlen($alphabet);
$num = substr($num, 0, -1);
}
return $decoded;
}
echo base_encode($Guid, $alphabet);
}
So for more stronger uniqueness, i am using the $Guid as the key generator. That should be ok right?
© Stack Overflow or respective owner