我试图在php中生成一个随机密码。

但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?

谢谢。

function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, count($alphabet)-1);
        $pass[$i] = $alphabet[$n];
    }
    return $pass;
}

当前回答

如果你在PHP7上,你可以使用random_int()函数:

function generate_password($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[random_int(0, $max)];

  return $str;
}

旧答案如下:

function generate_password($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[mt_rand(0, $max)];

  return $str;
}

其他回答

一句话:

substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') , 0 , 10 )

试着用大写字母,小写字母,数字和特殊字符

function generatePassword($_len) {

    $_alphaSmall = 'abcdefghijklmnopqrstuvwxyz';            // small letters
    $_alphaCaps  = strtoupper($_alphaSmall);                // CAPITAL LETTERS
    $_numerics   = '1234567890';                            // numerics
    $_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|';   // Special Characters

    $_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars;   // Contains all characters
    $password = '';         // will contain the desired pass

    for($i = 0; $i < $_len; $i++) {                                 // Loop till the length mentioned
        $_rand = rand(0, strlen($_container) - 1);                  // Get Randomized Length
        $password .= substr($_container, $_rand, 1);                // returns part of the string [ high tensile strength ;) ] 
    }

    return $password;       // Returns the generated Pass
}

假设我们需要10位Pass

echo generatePassword(10);  

示例输出:

IZCQ_IV \ 7

@wlqsfhT (d

是1!8 + 1 \ 4 @ud

安全警告:rand()不是一个加密安全的伪随机数生成器。在其他地方寻找在PHP中生成加密安全的伪随机字符串的方法。

试试这个(使用strlen而不是count,因为count在字符串上总是1):

function randomPassword() {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $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
}

Demo

Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too. function checkForCharacterCondition($string) { return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string); } $j = 1; function generate_pass() { global $j; $allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]'; $pass = ''; $length = 8; $max = mb_strlen($allowedCharacters, '8bit') - 1; for ($i = 0; $i < $length; ++$i) { $pass .= $allowedCharacters[random_int(0, $max)]; } if (checkForCharacterCondition($pass)){ return '<br><strong>Selected password: </strong>'.$pass; }else{ echo 'Iteration '.$j.': <strong>'.$pass.'</strong> Rejected<br>'; $j++; return generate_pass(); } } echo generate_pass();

一个简单的代码应该是这样的:

function generatePassword($len){
    $az = range("a","z");
    $AZ = range("A","Z");
    $num = range(0,9);
    $password = array_merge($az,$AZ,$num);
    return substr(str_shuffle(implode("",$password)),0, $len);
}
// testing 
$generate = range(8,32);
foreach($generate as $g){
    print "Len:{$g} = " . generatePassword($g)."\n";
}

输出:

Len:8 = G5uFhPKS
Len:9 = aU9x2NjvI
Len:10 = lJE9kxy3oD
Len:11 = tVh2CmpMdHW
Len:12 = ToXYHCPb58Ar
Len:13 = KIFVoLg5NdDzX
Len:14 = eFUabML28tXhf0
Len:15 = iegDCQcIMaxH0ST
Len:16 = sRvDmPo5IkaMqNO0
Len:17 = T5rwVDs6XGAqSU9KN
Len:18 = QwROWAfh1lpoCSaX0H
Len:19 = HP0trD4B9SQeUkNuAGV
Len:20 = P9Fdwqmu782ARHDiKGZM
Len:21 = 3Gxia9LPmCZM68dwe4YOf
Len:22 = ywFjuA2GDg0Oz8LVnCI94M
Len:23 = 16MiEVUgqPRueahlyvJfBz5
Len:24 = sPt0H9NSu5KrJTYeMXbOFgi7
Len:25 = QFKGTypaZlsMRnHPgNbVfIwxm
Len:26 = hbyJXtV81AEuMazS4GdFTINBUg
Len:27 = H3AiD95S4Z8xwMrz2L71GqUunaW
Len:28 = m8W2geIiO7Phc3H5Kyr1XCAs09Dv
Len:29 = MusNfYgOWnbrI62twRBvj38XEcDdi
Len:30 = VgNeILaRT2wvb4J7hzCMSHsquUBtnA
Len:31 = nhUvCxgOS94dsYjzBtcaTou1WIArMQP
Len:32 = AFSVQqCijuPMp0cGJNdDtzYX78erKB9w