Monday, November 29, 2010

PHP-generating unique ids...3 ways!!!

        1. Generate custom length unique id

<?php
//set the random id length $random_id_length 10;
//generate a random id encrypt it and store it in $rnd_id $rnd_id crypt(uniqid(rand(),1));
//to remove any slashes that might have come $rnd_id strip_tags(stripslashes($rnd_id));
//Removing any . or / and reversing the string $rnd_id str_replace(".","",$rnd_id); $rnd_id strrev(str_replace("/","",$rnd_id));
//finally I take the first 10 characters from the $rnd_id $rnd_id substr($rnd_id,0,$random_id_length);

echo 
"Random Id: $rnd_id" ;
echo 
"<br>";
?>

        2. Using uniqid() function

<?php
//creates a unique id with the 'about' prefix$a uniqid(about);
echo 
$a;
echo 
"<br>";
//creates a longer unique id with the 'about' prefix$b uniqid (abouttrue);
echo 
$b;
echo 
"<br>";
//creates a unique ID with a random number as a prefix - more secure than a static prefix $c uniqid (rand(), true);
echo 
$c;
echo 
"<br>";
//this md5 encrypts the username from above, so its ready to be stored in your database$md5c md5($c);
echo 
$md5c;
echo 
"<br>";
?>
        3. Generate custom length unique id

<?php
//set the random id length $random_id_length 10;
//generate a random id encrypt it and store it in $rnd_id $rnd_id crypt(uniqid(rand(),1));
//to remove any slashes that might have come $rnd_id strip_tags(stripslashes($rnd_id));
//Removing any . or / and reversing the string $rnd_id str_replace(".","",$rnd_id); $rnd_id strrev(str_replace("/","",$rnd_id));
//finally I take the first 10 characters from the $rnd_id $rnd_id substr($rnd_id,0,$random_id_length);

echo 
"Random Id: $rnd_id" ;
echo 
"<br>";
?>