繁体   English   中英

如何使用 PHP 创建随机密码生成器?

[英]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条件,然后再做一次。 我该如何编写这段代码?

  1. 您想使用random_int() ,而不是rand()
  2. 有一个名为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM