而不是改写字母表字符串,它是更快得到一个单一的随机字符。
从字符串中获取一个随机字符,然后将md5(time())附加到它。在添加md5(time())之前,从其中删除一个字符,以便将生成的字符串长度保持为32个字符:
substr( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,mt_rand( 0 ,51 ) ,1 ) .substr( md5( time() ), 1)
小写版本:
substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 )
或者甚至更短和一点点更快的小写版本:
chr( mt_rand( 97 ,122 ) ) .substr( md5( time( ) ) ,1 )
/* or */
chr( mt_rand( ord( 'a' ) ,ord( 'z' ) ) ) .substr( md5( time( ) ) ,1 )
对任何试图在一秒钟内生成许多随机字符串的任何人的注释:由于time()以秒为单位返回时间,md5(time())将在给定的第二次时间是相同的,因为如果许多随机字符串第二次,那些可能最终有一些重复。
我已经测试使用下面的代码。这测试小写版本:
$num_of_tests = 100000;
$correct = $incorrect = 0;
for( $i = 0; $i < $num_of_tests; $i++ )
{
$rand_str = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );
$first_char_of_rand_str = substr( $rand_str ,0 ,1 );
if( ord( $first_char_of_rand_str ) < ord( 'a' ) or ord( $first_char_of_rand_str ) > ord( 'z' ) )
{
$incorrect++;
echo $rand_str ,'
';
}
else
{
$correct++;
}
}
echo 'Correct: ' ,$correct ,' . Incorrect: ' ,$incorrect ,' . Total: ' ,( $correct + $incorrect );