PHP生成随 secret 码

标签 php

我整理了这个小脚本,它使用一个单词列表来生成一个可读的密码。

代码的第一部分可以很好地生成单词和数字。问题是最后的符号似乎只是偶尔起作用。

 <?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/

相关文章:

php - php问题中html中的引号

php - 清除 Canvas 并保存 Canvas

php - 列出依赖特定 GitHub repository/library/dependency 的所有存储库

php+mysqli while(false !== ($data = $mysqli_res->fetch_assoc)) 创建无限循环

php - 如果 PHP 中不存在,则复制一个文件并创建一个目录

php - 对于 MySQL TEXT 类型,我应该使用 PDO PARAM_LOB 还是 PARAM_STR?

php - 弹出通知 : execute php script using jquery if new record added to mysql

php - MySql 查询在 PhpMyAdmin 中耗时 0.16 秒,但在 Php 中耗时 10 分钟

javascript - Wordpress:使菜单链接的行为与 "more"按钮相同

php - ASP.net 与 PHP(选择什么)