我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
这里有简单的代码:
echo implode("",array_map(create_function('$s','return substr($s,mt_rand(0,strlen($s)),1);'),array_fill(0,16,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")));
这里有一个简单的指南:
要更改字符串的长度,请将16更改为另一个值。
若要从不同字符中选择,请更改字符串。
递归解决方案:
public static function _random(string $set , int $length): string
{
$setLength = strlen($set);
$randomKey = random_int(0, $setLength - 1);
$firstPiece = substr($set, 0, $randomKey);
$secondPiece = substr($set, $randomKey, $setLength - $randomKey);
$removedCharacter = $firstPiece[strlen($firstPiece) - 1] ?? null;
if(null === $removedCharacter || $length === 0) {
return '';
}
$firstPieceWithoutTheLastChar = substr($firstPiece, 0, -1);
return $removedCharacter . self::_random($firstPieceWithoutTheLastChar . $secondPiece, $length - 1);
}
不错的表现,https://3v4l.org/aXaJ6/perf
首先,定义你想要使用的字母:
$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);