我试图在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);
<?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 */
这段代码将帮助:
此函数将返回长度在$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;
}