Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random password with PHP?

Or is there a software to auto generate random passwords?

like image 520
user198729 Avatar asked Dec 03 '09 03:12

user198729


People also ask

How do I generate a random password in Wordpress?

generate_random_password( int $len = 8 ) Generates a random password.


2 Answers

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.

like image 60
Matt Huggins Avatar answered Oct 04 '22 06:10

Matt Huggins


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; } 
like image 38
Dolph Avatar answered Oct 04 '22 05:10

Dolph