簡體   English   中英

隨機字符串生成PHP

[英]Random string generation php

下面是生成隨機字符串的代碼,它正在工作,但是這里存在一些問題,我目前無法弄清楚這里發生的情況是它總是返回長度為1的值,我期望長度為10的隨機字符串。我也通過了10作為長度。 請指導我在這里做錯了什么。

<?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;
    }
}

?>

您從while內返回,導致while循環僅運行一次,並在該點返回結果(只有1個字符)

將返回行1向下移動(退出while循環),它應該可以工作。

只是好奇,乘以microtime()* 1000000的意義何在?

每次調用microtime()都會產生不同的種子!

似乎為我工作。

修正您的代碼:

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

您的return語句在while循環內。

將其移到while循環結束之后。

您的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;
}    
?>

我建議您也增加一個最大長度,以防萬一。

暫無
暫無

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

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