how to generate shortest possible string in php? [duplicate]
Possible Duplicate:
How to code a URL shortener?
How to generate shortest possible string (the way e.g. bit.ly is doing this)?
Well you would have to make random string and then check if you allredy have it in your database! Here i write you a example how to. Btw. this is just a quick one. There are much more things that could be checked to speed it up!
$cl=2;
$cr=0;
$n="";
while(!$e){
if($cr>500){$cr=0;$cl++;}
$n=genRandomString($cl);
$checker = mysql_query("select count(*) as haveit from table where thestring='".$n."'");
$xa = mysql_fetch_array($checker);
if($xa['haveit']==0){$e=1;}
$cr++;
}
function genRandomString($len){
$length = $len;
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
This is just to give you idea how to do it! This have to be optimized a little! :D
精彩评论