2011-11-21 316 views
0

下面是随机字符串生成的代码,它正在工作,但这里有一些问题,我目前无法弄清楚这里发生了什么,它总是返回长度为1的值,我期待一个长度为10的随机字符串。我也传递了10个长度。请引导我在这里做错了什么。随机字符串生成php

<?php 
function random_string($length) { 
    $len = $length; 
    $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"; 
    $max = strlen($base) - 1; 
    $activatecode = ''; 
    mt_srand((double) microtime() * 1000000); 

    while (strlen($activatecode) < $len + 1) { 
     $activatecode.=$base{mt_rand(0, $max)}; 

     return $activatecode; 
    } 
} 

?> 

回答

1

似乎为我工作。

修复您编写了一下:

function random_string($length) { 
$len = $length; 
$base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"; 
$max = strlen($base) - 1; 
$activatecode = ''; 
mt_srand((double) microtime() * 1000000); 

while (strlen($activatecode) < $len + 1) { 
    $activatecode.=$base[mt_rand(0, $max)]; 
} 

    return $activatecode; 
} 

演示:http://codepad.org/gq0lqmB3

6

您从而内返回,造成while循环只运行一次,并返回该点的结果(这是只有1个字符)

将您返回线路1倒(脱离while循环),它应该工作。

+0

/facepalm工作大声笑索姆时间复制粘贴是最糟糕的,那么你认为THx回答 –

+0

不客气;) – matthiasmullie

1

return语句是while循环内。

将它移到while循环结束之后。

1

您的return语句位于while循环内部,使其立即退出函数,并将其移至函数的末尾。

一些补充说明:

  • 无需mt_srand((double) microtime() * 1000000);时下。
  • 不要使用strlen,你不需要它。
  • {}子串语法已过时。

例子:

<?php 
function random_string($length) 
{ 
    $length = (int) $length; 
    if ($length < 1) return ''; 

    $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"; 
    $max = strlen($base) - 1; 

    $string = '';  
    while ($len--) 
    { 
     $string .= $base[mt_rand(0, $max)]; 
    } 
    return $string; 
}  
?> 

我建议你添加一个最大长度为好,以防万一。

1

只是好奇,什么是乘microtime()* 1000000?

每次microtime()被调用它都会产生不同的种子!