随机密码生成方法必须在每个生成的字符串上包含
a)符号b)大写字母c)小写字母d)数字。
但是我的输出会随机丢失所有这些。
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789$_.@!^%&*()-#";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
echo randomPassword();
修改您的方法并添加必需的符号明确地:
function randomPassword() {
$letter = "abcdefghijklmnopqrstuwxyz";
$upperLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
$numbers = "0123456789";
$signs = '$_.@!^%&*()-#';
$pass = array(); //remember to declare $pass as an array
// add a letter
$pass[] = $letters[rand(0, strlen($letters) - 1)];
// add an uppercase letter
$pass[] = $letters[rand(0, strlen($upperLetters) - 1)];
// add number and sign
$pass[] = $letters[rand(0, strlen($numbers) - 1)];
$pass[] = $letters[rand(0, strlen($signs) - 1)];
// add more chars
$alphabet = $letters . $upperLetters . $numbers . $signs;
for ($i = 0; $i < $yourLength; $i++) {
$n = rand(0, strlen($alphabet) - 1);
$pass[] = $alphabet[$n];
}
// shuffle chars in array so your passwords not always start with letter
shuffle($pass);
return implode($pass); //turn the array into a string
}
echo randomPassword();
进一步:
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789$_.@!^%&*()-#";
$pass = array(); //remember to declare $pass as an array
// numbers here are start and end positions of symbols groups
$pass[] = $alphabet[rand(0, 25)];
$pass[] = $alphabet[rand(26, 51)];
$pass[] = $alphabet[rand(52, 61)];
$pass[] = $alphabet[rand(62, 74)];
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < $yourLength; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
shuffle($pass);
return implode($pass); //turn the array into a string
}
echo randomPassword();
我认为这会有所帮助
<?php
function random_password_generate($length) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-=+?";
$password = substr(str_shuffle( $chars ),0, $length );
return $password;
}
$password = random_password_generate(8);
echo $password;
?>