我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
这段代码将帮助:
此函数将返回长度在$maxLength和$minLength之间的随机字符串。
注意:函数random_bytes从PHP 7开始工作。
如果你需要特定的长度,那么$maxLength和$minLength必须相同。
function getRandomString($maxLength = 20, $minLength = 10)
{
$minLength = $maxLength < $minLength ? $maxLength : $minLength;
$halfMin = ceil($minLength / 2);
$halfMax = ceil($maxLength / 2);
$bytes = random_bytes(rand($halfMin, $halfMax));
$randomString = bin2hex($bytes);
$randomString = strlen($randomString) > $maxLength ? substr($randomString, 0, -1) : $randomString;
return $randomString;
}
一个完整的解决方案(课程加测试),部分基于上面的一些建议…
class TokenFactory
{
private const LENGTH = 12;
private const ALLOWED = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ~!@#$%^&*{}';
private const MIN_NUMBER_OF_DIGITS = 1;
private const MIN_NUMBER_OF_CAPS = 1;
private const MIN_NUMBER_OF_SPECIALS = 1;
private const MIN_NUMBER_OF_LETTERS = 1;
/**
* @return string
* @throws \Exception
*/
public function make(): string
{
$pass = $this->generateToken();
if ($this->isTokenValid($pass)) {
return $pass;
} else {
return $this->make();
}
}
/**
* @return string
* @throws \Exception
*/
private function generateToken(): string
{
$allowedCharacters = self::ALLOWED;
$token = '';
$max = mb_strlen($allowedCharacters, '8bit') - 1;
for ($i = 0; $i < self::LENGTH; ++$i) {
$token .= $allowedCharacters[random_int(0, $max)];
}
return $token;
}
/**
* @param $token
* @return bool
*/
private function isTokenValid($token): bool
{
$numberOfDigits = preg_match_all("/[0-9]/", $token);
$numberOfCaps = preg_match_all("/[A-Z]/", $token);
$numberOfSpecials = preg_match_all("/[~!@#\$%^&*{}]/", $token);
$numberOfLetters = preg_match_all("/[a-z]/", $token);
return
$numberOfDigits > self::MIN_NUMBER_OF_DIGITS
&& $numberOfCaps > self::MIN_NUMBER_OF_CAPS
&& $numberOfSpecials > self::MIN_NUMBER_OF_SPECIALS
&& $numberOfLetters > self::MIN_NUMBER_OF_LETTERS
;
}
}
class TokenFactoryTest
{
public function test_correct_syntax()
{
/**
* Arrange
*/
$length = 12;
$numberOfChecks = 1000;
/**
* Act & Assert
*/
$class = new TokenFactory();
$i = 0;
while ($i < $numberOfChecks) {
$generatedToken = $class->make();
$numberOfDigits = preg_match_all( "/[0-9]/", $generatedToken );
$numberOfCaps = preg_match_all( "/[A-Z]/", $generatedToken );
$numberOfSpecials = preg_match_all("/[~!@#\$%^&*{}]/", $generatedToken);
$numberOfLetters = preg_match_all("/[a-z]/", $generatedToken);
Assert::assertEquals($length, strlen($generatedToken));
Assert::assertTrue($numberOfDigits >= 1, 'Digit error: ' . $generatedToken);
Assert::assertTrue($numberOfCaps >= 1, 'Caps error: ' . $generatedToken);
Assert::assertTrue($numberOfSpecials >= 1, 'Specials error: ' . $generatedToken);
Assert::assertTrue($numberOfLetters >= 1, 'Letters error: ' . $generatedToken);
$i++;
}
}
}
顺便说一句,请确保在适合您需要的地方捕获该异常!
另一个一行程序,生成一个包含字母和数字的10个字符的随机字符串。它将创建一个具有范围的数组(调整第二个参数以设置大小),循环遍历该数组并分配一个随机ASCII字符(范围0-9或a-z),然后内爆该数组以获得一个字符串。
$str = implode('', array_map(function () { return chr(rand(0, 1) ? rand(48, 57) : rand(97, 122)); }, range(0, 9)));
注意:这只适用于PHP 5.3及更高版本