How to generate random password with PHP?

落花浮王杯 提交于 2019-12-17 08:25:27

问题


Or is there a software to auto generate random passwords?


回答1:


Just build a string of random a-z, A-Z, 0-9 (or whatever you want) up to the desired length. Here's an example in PHP:

function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

To optimize, you can define $chars as a static variable or constant in the method (or parent class) if you'll be calling this function many times during a single execution.




回答2:


Here's a simple solution. It will contain lowercase letters and numbers.

substr(str_shuffle(strtolower(sha1(rand() . time() . "my salt string"))),0, $PASSWORD_LENGTH);

Here's A stronger solution randomly generates the character codes in the desired character range for a random length within a desired range.

function generateRandomPassword() {
  //Initialize the random password
  $password = '';

  //Initialize a random desired length
  $desired_length = rand(8, 12);

  for($length = 0; $length < $desired_length; $length++) {
    //Append a random ASCII character (including symbols)
    $password .= chr(rand(32, 126));
  }

  return $password;
}



回答3:


I want to play the game. The simplest way would be to do:

function rand_passwd( $length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
    return substr( str_shuffle( $chars ), 0, $length );
}

This is pretty much just a modification of the first answer. Specify the characters you want in the second parameters and the length of the password in the first.




回答4:


This is how I do it.

$pw = ""; 
for ($i = 0; $i < 13; $i++)
{
    $pw .= chr(rand(33, 126));
}



回答5:


here is a function that generates a password with a minimum length, a minimum number of digits and a minimal number of letters.

function generatePassword() {
$min_length=8;  //Minimum length of the password
$min_numbers=2; //Minimum of numbers AND special characters
$min_letters=2; //Minimum of letters

$password = '';
$numbers=0;
$letters=0;
$length=0;

while ( $length <= $min_length OR $numbers <= $min_numbers OR $letters <= $min_letters) {
    $length+=1;
    $type=rand(1, 3);
    if ($type==1) {
        $password .= chr(rand(33, 64)); //Numbers and special characters
        $numbers+=1;
    }elseif ($type==2) {
        $password .= chr(rand(65, 90)); //A->Z
        $letters+=1;
    }else {
        $password .= chr(rand(97, 122)); //a->z
        $letters+=1;
    }

}
return $password;   
}



回答6:


A good password should be a mixture of both uppercase, lowercase, has number, letters, has special characters and its more than 6 characters long. Here is function I use on my apps.

function randomPassword( $length = 8 ) 
{ 
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?"; 
$length = rand(10, 16); 
$password = substr( str_shuffle(sha1(rand() . time()) . $chars ), 0, $length );
 return $password;
}



回答7:


Also you can try a function that I wrote and is available form my blog. Advantage of this function is that it gives equal importance to lowercase, uppercase, numbers and special characters. It can be found here PHP random password generator function




回答8:


I like to shuffle array of random chars

$a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
shuffle($a);
echo implode($a); //maxlength
echo "\n".substr( implode($a), 0, 10 ); //instead of 10 => any length

//As function:
function getMeRandomPwd($length){
    $a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789"); 
    shuffle($a);
    return substr( implode($a), 0, $length );
}
echo "\n".getMeRandomPwd(8)."\n".getMeRandomPwd(11);
// Outpus something like:
// 3Ai4Xf6R2I8bYGUmKgB9jpqo7ncV5teuQhkOHJCNrTP0sLFd1wxSMlEWvyaD
// 3Ai4Xf6R2I
// JsBKWFDa
// gfxsjr3dX70

If you need the password to be longer, just concatenate charlist a few times :)




回答9:


You could just use PEAR's Text_Password package - it supports quite a few algorithms for generating them; and frees up your time to go onto something else.




回答10:


Pwgen-php produces save, pronounceable (easier to remember) passwords: http://code.google.com/p/pwgen-php/

Might that be acceptable?




回答11:


This function will generate more stronger password than most woted solution:

function generatePassword($size=8){
    $p = openssl_random_pseudo_bytes(ceil($size*0.67), $crypto_strong);
    $p = str_replace('=', '', base64_encode($p));
    $p = strtr($p, '+/', '^*');
    return substr($p, 0, $size);      
}

Each character of password will be [A-Z] or [a-z] or ^ or *




回答12:


function generate_password($length = 6) {
    $password = '';
    $chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
    for ($i = 0; $i < $length; $i ++) {
        $password .= $chars[array_rand($chars)];
    }
    return $password;
}



回答13:


This will help to create random password :

<?php
function generatePassword ($length = 8)
{
  $genpassword = "";
  $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
  $i = 0; 
  while ($i < $length) { 
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    if (!strstr($genpassword, $char)) { 
      $genpassword .= $char;
      $i++;
    }
  }
  return $genpassword;
} 
?>
<input type="text" value="<?php echo generatePassword(); ?>">

Here is the working example (Demo)




回答14:


use hackzilla/password-generator

it has many options to create different kind of passwords:

  • ComputerPasswordGenerator()
  • HybridPasswordGenerator() -> sjgX-PFjH-zxMz-PRDz-G6mx-wMJ4-ST24
  • HumanPasswordGenerator() -> Verkuemmerungen-verlottertet-dreinzuschauen (word list based. in this case a german word list)
  • RequirementPasswordGenerator()

ComputerPasswordGenerator

$generator
  ->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASE, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASE, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERS, true)
  ->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLS, false)
;

$password = $generator->generatePassword();

RequirementPasswordGenerator

$generator
  ->setLength(16)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_UPPER_CASE, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_LOWER_CASE, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_NUMBERS, true)
  ->setOptionValue(RequirementPasswordGenerator::OPTION_SYMBOLS, true)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 2)
  ->setMinimumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 2)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 8)
  ->setMaximumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 8)
;

$password = $generator->generatePassword();



回答15:


Another, very simple (and secure!) way to do this is the following (I generate all my own passwords that way):

base64_encode(random_bytes(12));

This generates a 16 character password that uses quite a sane range of characters.

However, depending on your requirements (for example if a user needs to type in their password), it may be desirable to remove characters that migth be confused (such as l, I, 1, 0, O, 5, S, and so on). In that case, the above solution is probably a bit too simple.




回答16:


I use st_split and implode function:

function genarateKey(){
    $limit= 8;
    $chars= 'abcdefghijklmnopqrstuvxwyz1234567890!@#$%^&*()_+=-[]{}\|ABCDEFGHIJKLMNOPQRSTUVXWYZ';
    $chararray= str_split($chars);
    $gen=array();
    for($i=0;$i<$limit;$i++){
        $index=rand(0,strlen($chars)-1);
        $gen[$i]= $chararray[$index];
    }
    return implode($gen); //converts array to string
}



回答17:


Memorable password generator

function password($length)
  {
    $vowel = array(
        'a',
        'e',
        'i',
        'o',
        'u',
    );

    $consonant = array(
        'b',
        'c',
        'd',
        'f',
        'g',
        'h',
        'j',
        'k',
        'l',
        'm',
        'n',
        'p',
        'q',
        'r',
        's',
        't',
        'v',
        'w',
        'x',
        'y',
        'z',
    );

    $result = '';
    for ($i = 0; $i < $length; $i++) {
        if ($i % 2 == 0) {
            $result .= $consonant[rand(0, 15)];
        } else {
            $result .= $vowel[rand(0, 4)];
        }
    }

    return $result;
}

The result:

password(8);//kutekaku
password(11);//rahubabatul



回答18:


This function will include half digits and half numbers:

     function generateMixedPassword($length = 8) {
        $base = 'abcdefghijklmnopqrstuvwxyz';
        $baseD = '0123456789';

        $r = array();

        for ($i = 0; $i < $length; $i += 2) {
            $r[] = substr($base, rand(0, strlen($base) - 1), 1);
        }
        for ($i = 0; $i < $length; $i += 2) {
            $r[] = substr($baseD, rand(0, strlen($baseD) - 1), 1);
        }
        shuffle($r);

        return implode('', $r);
    }

Using the same login, it can be extended to also include special characters




回答19:


I think better way to generate random password is below function, if someone want then you can use these for strong password

public function randPassword($upper = 2, $lower = 3, $numeric = 2, $other = 1) { 

        $pass_order = Array(); 
        $passWord = ''; 

        //Create contents of the password 
        for ($i = 0; $i < $upper; $i++) { 
            $pass_order[] = chr(rand(65, 90)); 
        } 
        for ($i = 0; $i < $lower; $i++) { 
            $pass_order[] = chr(rand(97, 122)); 
        } 
        for ($i = 0; $i < $numeric; $i++) { 
            $pass_order[] = chr(rand(48, 57)); 
        } 
        for ($i = 0; $i < $other; $i++) { 
            $pass_order[] = chr(rand(33, 47)); 
        } 

        //using shuffle() to shuffle the order
        shuffle($pass_order); 

        //Final password string 
        foreach ($pass_order as $char) { 
            $passWord .= $char; 
        } 
        return $passWord; 
    } 


来源:https://stackoverflow.com/questions/1837432/how-to-generate-random-password-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!