» Birthday Bundle - Over $400 worth of Envato files for just $20

How to generate a random password in PHP

Posted on August 29, 2008, Filled under PHP,  Bookmark it

This function generates random passwords. It’s useful when you have to reset someone’s account or when you create accounts that need a default password.

<?php
/*
Credits: Bit Repository

http://www.bitrepository.com/web-programming/php/generating-a-random-password.html

*/
function generate_random_password($chars = 7, $type = '')
{
$letters_array = range('a','z');
$numbers_array = range(1,9);

srand((float) microtime() * 10000000); // if PHP Version < 4.2.0 

if($type == 'letters')
{
$array = $letters_array;
}
else if($type == 'numbers')
{
$array = $numbers_array;
}
else
{
$array = array_merge($letters_array, $numbers_array);
}

$rand_keys = array_rand($array, $chars);

$password = '';

foreach($rand_keys as $key)
	{
	$password .= $array[$key];
	}

return $password;
}

$password = generate_random_password();

// Outputs a 7 characters password (default)
echo $password;

$password = generate_random_password(10);

// Outputs a 10 characters password
echo $password;
?>


If you wish to generate a 10 characters password containing only numbers then here's how you can do it:
$new_password = generate_random_password(10,'numbers');

// Outputs a numeric password containing only numbers.
echo $new_password;

NOTE: You can add ‘letters’ for the second parameter if you want to have only letters in the password.

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

2 Replies to "How to generate a random password in PHP"

  1. Good stuff, thanks, I might use this in my next custom CMS

  2. hi..can i ask something? how can i create a new user account, let it have a default password that had been set,for example the default password is “welcome”…and this default password will be the same for all new user. Then user need to sign int otheir account, and they will have to change their default password into a new password.

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)