[英]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.