Random password generation in PHP is a fairly simple, however one of the problems I often find is I’m left with a password made up entirely of numbers or letters with no special characters what so ever. Take for example the following function;

01
02
03
/*
04
* Altroleet.com 2011
05
*/
06
07
// Generate a password with a guarantee of lowercase, uppercase, numbers and special characters
08
function generate_password($len = 8) {
09
 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!"$%^&*()_+-=[]{}:;@#~<>?';
10
 $password = '';
11
 
12
 for ($i = 0; $i < $len; $i++)
13
 $password .= $chars[rand(0, strlen($chars) - 1)];
14
 
15
 return $password;
16
}
17
18
echo generate_password();
19
20
echo '

';
21
22
echo generate_password(3);
23
24
echo '

';
25
26
echo generate_password(16);
27
28
?>

On most occasions it will return a string made up of a wide variety of characters, however you aren’t guaranteed a secure password. While unlikely it is possible to generate normal dictionary hackable words or strings made up of entirely one character. You can solve this be forcing the function to select characters from four different sources; upper case, lower case, numbers and special characters. E.G

01
02
03
/*
04
* Altroleet.com 2011
05
*/
06
07
// Generate a password with a guarantee of lowercase, uppercase, numbers and special characters
08
function generate_password($len = 8) {
09
 $chars = Array('abcdefghijklmnopqrstuvwxyz',
10
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
11
    '01234567890',
12
    '!"$%^&*()_+-=[]{}:;@#~<>?');
13
 $len = (($len < count($chars)) ? count($chars) : $len);
14
 $per_sec = floor($len / count($chars));
15
16
 $password = '';
17
 for ($i = 0, $max = count($chars); $i < $max; $i++) {
18
 for ($j = 0, $amount = (($i + 1 < $max) ? $per_sec : ($len - ($per_sec * (count($chars) - 1)))); $j < $amount; $j++) {
19
 if (strlen($password) == 0)
20
 $password = $chars[$i][rand(0, strlen($chars[$i]) - 1)];
21
 else
22
 $password = substr($password, 0, ($split_point = rand(0, strlen($password)))).$chars[$i][rand(0, strlen($chars[$i]) - 1)].substr($password, $split_point, strlen($password) - $split_point);
23
 }
24
 }
25
 
26
 return $password;
27
}
28
29
echo generate_password();
30
31
echo '

';
32
33
echo generate_password(3);
34
35
echo '

';
36
37
echo generate_password(16);
38
39
?>

This code is slower than the first function, however you get more reliable results and unless you are batch resetting a large amount of passwords you are unlikely to notice a difference. Especially when the auto generate password is one of the least used functions in a user system.

Basic flip clock images that were made for a really old university project, I find that they still come in handy for websites and games. Feel free to use and modify;

   

Download Zip File [contains 21 files]

© 2014 Altroleet Suffusion theme by Sayontan Sinha