Working on a link shortening script and I'm stumped. I figured the following code would function as needed however, I get an execution time out related to $str .= $charset[mt_rand(0, $count-1)];
. I have scoured over the code several times, I can't find what I am doing wrong.
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
function shrinkURL($url) {
$is_unique = false;
$num = 4;
$random_string = randString($num);
$count = 0;
while (!$is_unique) {
$q1 = "SELECT id FROM linkShortner WHERE short = '".$random_string."' LIMIT 1";
$result = mysql_query($q1) or die(mysql_error());
if ($result === false) // if you don't get a result, then you're good
$is_unique = true;
else // if you DO get a result, keep trying
$count++;
if ($count >= 10) {
$num = (strlen($random_string) + 1);
$random_string = randString($num);
$count = 0;
}
$random_string = randString($num);
}
$shortURL = "https://domain.com/l/".$random_string;
$q2 = "INSERT INTO linkShortner (id, destination, short, shorURL, creationDate) VALUES (NULL, '".$url."', '".$random_string."', '".$shortURL."', '".$DateTime."')";
$r2 = mysql_query($q2) or die(mysql_error());
return $shortURL;
}
$shortURL = shrinkURL('http://domain.com');
echo $shortURL;
Any help would be greatly appreciated, think maybe I am just burnt out.