While creating a password recovery system for one of my projects, I had to generate random password. I could have written a function at my own, but had a very tight deadline for this feature. Thus I went on googling for it and came across a very cool function at this link.

The post not just saved my valuable time, I was so impressed with it that I decided to write a post for this function it self.

The function goes like this:

function generatePassword($length=6,$level=2)
$usec, $sec) = explode(‘ ‘, microtime());
srand((float) $sec + ((float) $usec * 100000));

$validchars[1] = “0123456789abcdfghjkmnpqrstvwxyz”;
$validchars[2] = “0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;
$validchars[3] = “0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/”;

$password = “”;
$counter = 0;

while ($counter < $length) {
$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

// All character must be different
if (!strstr($password, $actChar)) {
$password .= $actChar;

return $password;


Leave a Reply

Your email address will not be published. Required fields are marked *