PHP生成随机密码

时间:2011-11-29 11:28:42

标签: 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>

1 个答案:

答案 0 :(得分:6)

你似乎得到一个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];