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!
- August 29, 2008
- article by Gabriel C.
- 2 comments
Related Posts
Validate (input) passwordat August 30, 2008 with 2 comments
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
PHP: Usage of Range() Function (Alphabetical & Numerical Output)at September 2, 2008
Display Values from an Array in Random Orderat October 2, 2008
Basic PHP Captcha (Image Verification) with Refresh Featureat February 10, 2009 with 21 comments

2 Replies to "How to generate a random password in PHP"
August 29, 2008 at 7:40 AM
Good stuff, thanks, I might use this in my next custom CMS
January 14, 2010 at 3:21 PM
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.