我有这个函数用于生成随机字符串。这工作但我需要生成一个数字和一个字母总是随机字符串。
function random() {
$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
}
如何编辑我的代码并在随机字符串中生成一个数字和字母。
答案 0 :(得分:0)
这样可行,但请记住,这是一种制作密码的可靠方法。
function random() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()_+=-";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
$pass[] = $alphabet[rand(0, 49)]; // Grab a random letter.
$pass[] = $alphabet[rand(50, 59)]; // Grab a random number.
for ($i = 0; $i < 6; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
shuffle($pass);
return implode($pass); //turn the array into a string
}
这是一个稍微好一点的版本,它使用了一些真正的伪熵。
function random() {
srand(time());
mt_srand(rand());
srand(mt_rand());
// You might also want to use openssl_random_pseudo_bytes() if available and
// not on a Windows w/PHP < 5.3 host.
// On Linux, think about including from /dev/urandom.
$entropy = str_split(hash('sha256', uniqid('awesomesalt', TRUE) . mcrypt_create_iv(64) . microtime() . rand() . mt_rand(), TRUE));
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()_+=-";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet); //put the length in cache
$rand = floor(ord(array_pop($entropy)) * 50 / 255.1);
$pass[] = $alphabet[0 + $rand]; // Grab a random letter.
$rand = floor(ord(array_pop($entropy)) * 10 / 255.1);
$pass[] = $alphabet[50 + $rand]; // Grab a random number.
for ($i = 0; $i < 6; $i++) {
$rand = floor(ord(array_pop($entropy)) * $alphaLength / 255.1);
$pass[] = $alphabet[$rand];
}
shuffle($pass);
return implode($pass); //turn the array into a string
}