duancan2539 2014-03-26 15:25
浏览 29

PHP函数调用函数

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.

  • 写回答

2条回答 默认 最新

  • doulong1987 2014-03-26 15:35
    关注

    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 )

    评论

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False