簡體   English   中英

PHP函數調用函數

[英]PHP Function Calling Function

使用鏈接縮短腳本,我很困惑。 我認為以下代碼可以根據需要運行,但是,我得到了與$str .= $charset[mt_rand(0, $count-1)];相關的執行超時$str .= $charset[mt_rand(0, $count-1)]; 我已經多次檢查代碼,找不到我做錯了的事情。

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;

任何幫助將不勝感激,認為也許我只是精疲力盡。

我的猜測是,在某個時候您的函數randString()將以$length參數為0的方式被調用。

這將使:

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

陷入困境,因為第一次迭代將是while (-1) ,這是正確的。 然后, while (-2) ,也是如此.. etc etc etc.

我會將您的while ( $length-- )更改為while ( $length-- >= 0 )

if ($result === false)更改為if (!mysql_num_rows($result)) ,一切都很好。 if ($result === false)用於mysqli,此處未使用。

基本上,rinkleURL函數會在嘗試插入唯一的字符串/行之前在數據庫中搜索匹配的字符串, if ($result === false)永遠不會為false,因為$result的值是MySQL_query($q1)因此會產生無限環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM