[英]How to create Random Password Generator using PHP?
这可以生成随机密码。
<?php
function randomPassword() {
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 26; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass);
}
echo randomPassword();
?>
但我想将此密码保存在passwords.txt
文件中。 下次创建新密码时,它会检查这个密码是否在那个passwords.txt
中。 而不是回声。 如果密码已经有,那么 go 到else
条件,然后再做一次。 我该如何编写这段代码?
random_int()
,而不是rand()
。file_put_contents()
的 function 可让您写入文件。 它甚至具有 append 模式。例如:
<?php
declare(strict_types=1);
function randomPassword(int $passwordLength = 26): string {
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < $passwordLength; $i++) {
$n = random_int(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass);
}
$random = randomPassword();
file_put_contents(
'passwords.txt',
$random . "\n",
FILE_APPEND
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.