我试图在PHP中创建一个随机字符串,我得到绝对没有输出:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring = $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

你的代码有3个问题:

$randstring没有赋值给任何东西(只在超出作用域的函数内部)。 RandomString只返回最后一个随机字符。用。=替换=。 Rand不生成加密安全的伪随机数。请改用random_int。

见下文:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring .= $characters[random_int(0, strlen($characters))];
        }
        return $randstring;
    }
    $randstring = RandomString();
    echo $randstring;

其他回答

<?php
    /**
     * Creates a random string
     *
     * @param (int) $length
     *   Length in characters
     * @param (array) $ranges
     *   (optional) Array of ranges to be used
     *
     * @return
     * Random string
    */
    function random_string($length, $ranges = array('0-9', 'a-z', 'A-Z')) {
        foreach ($ranges as $r) $s .= implode(range(array_shift($r = explode('-', $r)), $r[1]));
        while (strlen($s) < $length) $s .= $s;
        return substr(str_shuffle($s), 0, $length);
    }

    // Examples:
    $l = 100;
    echo '<b>Default:</b> ' . random_string($l) . '<br />';
    echo '<b>Lower Case only:</b> ' . random_string($l, array('a-z')) . '<br />';
    echo '<b>HEX only:</b> ' . random_string($l, array('0-9', 'A-F')) . '<br />';
    echo '<b>BIN only:</b> ' . random_string($l, array('0-1')) . '<br />';

/* End of file */
function rndStr($len = 64) {
     $randomData = file_get_contents('/dev/urandom', false, null, 0, $len) . uniqid(mt_rand(), true);
     $str = substr(str_replace(array('/','=','+'),'', base64_encode($randomData)),0,$len);
    return $str;
}

下面是一个简单的单行程序,它生成一个真正的随机字符串,而不需要任何脚本级循环或使用OpenSSL库。

echo substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', mt_rand(1,10))), 1, 10);

把它分解,这样参数就清楚了

// Character List to Pick from
$chrList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Minimum/Maximum times to repeat character List to seed from
$chrRepeatMin = 1; // Minimum times to repeat the seed string
$chrRepeatMax = 10; // Maximum times to repeat the seed string

// Length of Random String returned
$chrRandomLength = 10;

// The ONE LINE random command with the above variables.
echo substr(str_shuffle(str_repeat($chrList, mt_rand($chrRepeatMin,$chrRepeatMax))), 1, $chrRandomLength);

此方法的工作原理是随机重复字符列表,然后打乱组合的字符串,并返回指定的字符数。

您可以进一步随机化它,通过随机化返回字符串的长度,将$chrRandomLength替换为mt_rand(8,15)(用于8到15个字符之间的随机字符串)。

在PHP中生成随机字符串的另一种方法是:

function RandomString($length) {
    $original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
    $original_string = implode("", $original_string);
    return substr(str_shuffle($original_string), 0, $length);
}
echo RandomString(6);

要把它放在一行中,试试这个:

$str = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 5)), 0, $length);