snippets / Generate random password

Language: Php - First posted by Xrogaan on 2007-12-2 16:19 (11 months, 3 weeks)
Link to the snippet: http://www.friendsnippets.org/snippet/125/

A fully password generator.

 1 <?php
2
3 /**
4 * Generate random password
5 *
6 * @param integer $length Length of the generated password
7 * @param boolean $allow_uppercase
8 * @param boolean $allow_lowercase
9 * @param boolean $allow_numbers
10 * @param boolean $allow_special
11 * @param boolean $fix_similar If true, check if string contains mistakeable chars, add if accepted
12 * @param string $valid_charset
13 * @return string
14 */
15 function rpassword($length = 8, $allow_uppercase = 1, $allow_lowercase = 1, $allow_numbers = 1, $allow_special = 0, $fix_similar = 0, $valid_charset = "") {
16 // Create a list of usable chars based upon the parameters
17 if (!$valid_charset) {
18 if ($allow_uppercase) $valid_charset .= 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
19 if ($allow_lowercase) $valid_charset .= 'abcdefghijklmnopqrstuvxyz';
20 if ($allow_numbers) $valid_charset .= '0123456789';
21 if ($allow_special) $valid_charset .= '!#$%&()*+-./;<=>@\_';
22 }
23 // Find the charset length
24 $charset_length = strlen($valid_charset);
25 // If no chars is allowed, return false
26 if ($charset_length == 0) return false;
27 // Initialize the password and loop till we have all
28 $password = "";
29 while(strlen($password) < $length) {
30 // Pull out a random char
31 $char = $valid_charset[mt_rand(0, ($charset_length-1))];
32
33 if (($fix_similar && !strpos('O01lI5S', $char)) || !$fix_similar) $password .= $char;
34 }
35
36 return $password;
37 }
In order to post a comment, you should have a friendsnippet account. Please sign-in.

0 comments

Dec '07
  • A fully password generator.