PHP Random Password Generation Tutorial
Ranked #3,604 in Internet, #201,572 overall
Generating random passwords in PHP
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
01234567890123456789
Now there's 2 methods to use this charset for generating random passwords:
1. Picking characters from the charset with random positions (and so random characters are picked).
2. Shuffling the charset and picking characters at first position (which is different every time the charset is shuffled and one character is picked).
We'll start with creating the structure of our function to generate random passwords with.
Function: randomStr
Creating the random password generating function.
function randomStr( parameters ) {
function code
}
function randomStr($length, $charset) {
function code
}
function randomStr($length, $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
01234567890123456789") {
function code
}
function randomStr($length, $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
01234567890123456789") {
$str = "";
for($i=0;$i<$length;$i++) {
add random character of $charset to $str.
}
return $str;
}
Now all we need to do more is write the code to add a random charater to $str inside of the for loop ( which repeats it $length amount of times ).
Picking a random character (method 1)
Picking a random character by picking a character from a random position.
$pos = mt_rand(0, strlen($charset)-1);
$pos = mt_rand(0, strlen($charset)-1);
$str .= $charset[$pos];
function randomStr($length, $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
01234567890123456789") {
$str = "";
for($i=0;$i<$length;$i++) {
$pos = mt_rand(0, strlen($charset)-1);
$str .= $charset[$pos];
}
return $str;
}
Picking a random character (method 2)
Picking a random character by shuffling the charset and picking the first character.
$charset = str_shuffle($charset);
$str .= $charset[0];
function randomStr($length, $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
01234567890123456789") {
$str = "";
for($i=0;$i<$length;$i++) {
$charset = str_shuffle($charset);
$str .= $charset[0];
}
return $str;
}
Next PHP Tutorial
You might also like ...
Related Products (Amazon)
Related Products (eBay)
by webcodez
"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."
webcodez
GameHeroes
more »
- 21 featured lenses
- Winner of 14 trophies!
- Top lens » PHP & MySQL Poll System Tutorial
Explore related pages
- PHP & MySQL Poll System Tutorial PHP & MySQL Poll System Tutorial
- PHP & MySQL Visitors Counter Tutorial PHP & MySQL Visitors Counter Tutorial
- PHP & MySQL Login System Tutorial PHP & MySQL Login System Tutorial
- PHP basics tutorial PHP basics tutorial
- PHP Banner Rotator Tutorial PHP Banner Rotator Tutorial
- PHP Smilies System Tutorial PHP Smilies System Tutorial