Generating a Random User Password in PHP

Creating a custom random password generator in PHP isn’t difficult, for my purposes I often use this simple function

// $group is the characters we want the password possibly composed of
// $pass_length is the length we want our password to be
function random_password($group, $pass_length){
	for($p=0; $p<$pass_length; ++$p){
		// pick a random number, based on the time
		$random_num	= rand(0, ((double) microtime()* 1000000)) % 67;

		// user the random number to pick a character from $group and add it to the password
		$pass		= $pass.substr($group, $random_num, 1);
	return $pass;

Now to use this function all you need to do is set a group of characters you’d like to allow in your passwords and a password length. You could do something like this

$password	= random_password('tkmF#w8EcRzW6GvOPfcgNsQD1hArU4Y$Lx2a7Mu0jT3B!q5SyXJCheInpKZbHV9', 10);

which would give you passwords that are all ten characters long. Or if you want to vary that you could do something like this

$password	= md5( random_password('abcdefghijklmnopqrstuvwxyz1234567890', rand(8,16)) );

which would give you passwords that are between eight and sixteen characters long compose of lowercase letters a through z and numbers 0 through 9 AND encrypt it into md5 format which is a good way to store things in a MySQL database.

Of course, this is perfect for everyone, but it should get you in the right direction. Feel free to use and build on this code. Oh, an of course while this code is freely offered and works just great for me I can’t guarantee it is suitable for all purpose or be held liable for any damages if you somehow manage to become damaged by using this code.