我整理了这个小脚本,它使用一个单词列表来生成一个可读的密码。
代码的第一部分可以很好地生成单词和数字。问题是最后的符号似乎只是偶尔起作用。
<?php
function random_readable_pwd($length=10){
// the wordlist from which the password gets generated
// (change them as you like)
$words = 'AbbyMallard,AbigailGabble,AbisMal,Abu,Adella,TheAgent,AgentWendyPleakley,Akela,AltheAlligator,Aladar,Aladdin,AlamedaSlim,AlanaDale,Alana,Alcmene,Alice,AmeliaGabble,AmosSlade,Amphitryon,AnastasiaTremaine,Anda,Andrina,Angelique,AngusMacBadger';
// Split by ",":
$words = explode(',', $words);
if (count($words) == 0){ die('Wordlist is empty!'); }
// Add words while password is smaller than the given length
$pwd = '';
while (strlen($pwd) < $length){
$r = mt_rand(0, count($words)-1);
$pwd .= $words[$r];
}
$num = mt_rand(1, 99);
if ($length > 2){
$pwd = substr($pwd,0,$length-strlen($num)).$num;
} else {
$pwd = substr($pwd, 0, $length);
}
$pass_length = strlen($pwd);
$random_position = rand(0,$pass_length);
$syms = "!@#$%^&*()-+?";
$int = rand(0,51);
$rand_char = $syms[$int];
$pwd = substr_replace($pwd, $rand_char, $random_position, 0);
return $pwd;
}
?>
<html><head><title>Password generator</title></head>
<body>
<h1>Password generator</h2>
<p>
<?php
echo random_readable_pwd(10);
?>
</p>
</body>
</html>
最佳答案
您似乎获得了 0 到 51 之间的随机数,但 $syms 字符串中只有 13 个字符。应该是:
$syms = "!@#$%^&*()-+?";
$int = rand(0,12);
$rand_char = $syms[$int];
尚未对此进行测试,但我认为这是问题所在。
或者更好的是,获取 string's length :
$syms = "!@#$%^&*()-+?";
$int = rand(0,strlen($syms)-1);
$rand_char = $syms[$int];
关于PHP生成随 secret 码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309980/