简体   繁体   中英

PHP Function Calling Function

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.

My guess is that at some point your function randString() will be called with the $length argument being 0.

This would make:

while ($length--) {
    $str .= $charset[mt_rand(0, $count-1)];
}

get stuck, because the first iteration would be while (-1) , which is true. And then while (-2) , which is also true.. etc etc etc.

I would change your while ( $length-- ) to while ( $length-- >= 0 )

Changed if ($result === false) to if (!mysql_num_rows($result)) and all is well. if ($result === false) is for mysqli which is not being used here.

Basically the shrinkURL function scours the DB for a matching string before trying to insert a unique string/row, if ($result === false) would never = false because the value of $result is MySQL_query($q1) therefore producing an endless loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM