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

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

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

首先,定义你想要使用的字母:

$alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$special  = '~!@#$%^&*(){}[],./?';
$alphabet = $alphanum . $special;

然后,使用openssl_random_pseudo_bytes()生成适当的随机数据:

$len = 12; // length of password
$random = openssl_random_pseudo_bytes($len);

最后,使用这些随机数据创建密码。因为$random中的每个字符可以是chr(0)直到chr(255),代码使用其序数与$alphabet_length除法后的余数来确保只从字母表中选择字符(注意这样做会偏向随机性):

$alphabet_length = strlen($alphabet);
$password = '';
for ($i = 0; $i < $len; ++$i) {
    $password .= $alphabet[ord($random[$i]) % $alphabet_length];
}

或者,通常更好的方法是使用RandomLib和SecurityLib:

use SecurityLib\Strength;

$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new Strength(Strength::MEDIUM));

$password = $generator->generateString(12, $alphabet);

其他回答

你完全做错了,因为你依赖于数字,而不是字符,我不确定如果你想要随机输出只是数字,如果是这样,为什么需要得到所有的字母和所有的数字,并提取它们的长度?为什么不用rand(0,62)呢?,即使你在声明函数之前忘记初始化变量$randstring。

不管怎样,PHP为此目的提供了一个非常方便的函数。它的作用是()。下面是一个适合您需要的例子。

< ?php 函数随机字符串(){ $字符= '0123456789abcdefghijklmnopqrstuvwxyz '; 返回str_shuffle($字符); } echo randomString ();

一条线的解决方案是

str_shuffle(base64_encode(date('mdyhis').date('mdyhis')));

使用random_bytes函数生成加密安全的随机字节。

$bytes = random_bytes(16);
echo bin2hex($bytes);

可能的输出

da821217e61e33ed4b2dd96f8439056c

使用openssl_random_pseudo_bytes函数生成伪随机字节。

$bytes = openssl_random_pseudo_bytes(16);
echo bin2hex($bytes);

可能的输出

e2d1254506fbb6cd842cd640333214ad

最好的用例是

function getRandomBytes($length = 16)
{
    if (function_exists('random_bytes')) {
        $bytes = random_bytes($length / 2);
    } else {
        $bytes = openssl_random_pseudo_bytes($length / 2);
    }
    return bin2hex($bytes);
}
echo getRandomBytes();

可能的输出

ba8cc342bdf91143

如果您在用户可能看到或使用它的地方使用这个随机字符串(例如作为密码生成器),您可能希望限制用于排除元音的字符集。这样你就不会不小心说脏话,也不会冒犯别人。别笑,这是常有的事。

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