Jumat, 04 September 2009

Generate a random password in php

Today we will be seeing a small easy function to generate a password of specified length.

For this we will be creating a function called "genpwd()"



Now this function is ready, now we want to display the generated password of our specified length.
For this we will print the function value, specifying the length of the password to be generated.



The full working sample example is here, you can copy and paste this code to try it out. It will generate a random string everytime you refresh the page.



function genpwd($cnt)
{
// characters to be included for randomization, here you can add or delete the characters


$pwd = str_shuffle('abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#%$*');


// here specify the 2nd parameter as start position, it can be anything, default 0
return substr($pwd,0,$cnt);
}

echo genpwd(10); // specify the length of the generated password



UPDATE : 12th September 2009 Hey thanks Filip. Here is one more function to generate a random password suggested by Filip in comments below.


function passwordGenerator($length = null)
{
$pass = md5(time());
if($length != null) {
$pass = substr($pass, 0, $length);
}
return $pass;
}
echo passwordGenerator(6);


UPDATE : 17th December 2009. Hey thanks Fredrik Karlström. Here is one more function to generate a random password suggested by Fredrik Karlström in comments below



function generate_password($len = 8) {
$chars = str_split('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#');
$pwd = '';

for($i=0; $i < $len; $i++)
$pwd .= $chars[rand(1, $sizeof($chars)) -1];
return $pwd;
}

Tidak ada komentar:

Posting Komentar