I was working on Url Shortner script and I needed a better algorithm that can generate a fixed length random string which have very less probability of collision with other strings in db. So I created one simple, yet efficient algorithm. I hope this is good. It returns you 8 character long random string.
Expecting your advices and suggestions to improve it more.
PHP Code:
<?php
//////////////////////////////////////
// Author: Kishan Gor a.k.a Ksg91
// Date: 27-12-2010
/////////////////////////////////////
//returns 8 character long random string
function getKSGRandomString()
{
$a=array("0"=>"0","1"=>"1","2"=>"2","3"=>"3","4"=>"4","5"=>"5","6"=>"6","7"=>"7","8"=>"8","9"=>"9","10"=>"a","11"=>"b","12"=>"c","13"=>"d","14"=>"e","15"=>"f","16"=>"g","17"=>"h","18"=>"i","19"=>"j","20"=>"k","21"=>"l","22"=>"m","23"=>"n","24"=>"o","25"=>"p","26"=>"q","27"=>"r","28"=>"s","29"=>"t","30"=>"u","31"=>"v","32"=>"w","33"=>"x","34"=>"y","35"=>"z","36"=>"A","37"=>"B","38"=>"C","39"=>"D","40"=>"E","41"=>"F","42"=>"G","43"=>"H","44"=>"I","45"=>"J","46"=>"K","47"=>"L","48"=>"M","49"=>"N","50"=>"O","51"=>"P","52"=>"Q","53"=>"R","54"=>"S","55"=>"T","56"=>"U","57"=>"V","58"=>"W","59"=>"X","60"=>"Y","61"=>"Z");
$rand1=mt_rand(00000000,99999999);
$rand2=mt_rand(00000000,99999999);
$string='';
while($rand1>0)
{
$x = $rand1 % 100;
$rand1=floor($rand1/100);
$x = $x % 60;
$string.=$a[$x];
}
while($rand2>0)
{
$x = $rand2 % 100;
$rand2=floor($rand2/100);
$x = $x % 60;
$string.=$a[$x];
}
return $string;
}
?>
Comment