Simple random password generator in PHP

Posted on December 8th, 2009 in IT-babble

Lately I have encountered the need for random password generators in several of my clients’ projects. Applications vary from anti-spambot security codes to automatic password generating. To retain a flexible solution applicable in all those circumstances and more I have created a simple function in PHP.

The function can be called with 2 arguments, the first controlling the lenght of the output string and the second sets the allowed characters. Both of these are optional, if you call the function without arguments a six character long alphanumeric string will be generated.

function generatePassword($length = 6,
		$chars = '0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
	$password = '';
	$char_length = strlen($chars);
	srand((double)microtime()*1000000);
	for ($i = 0; $i < $length; $i++)
	{
		$num = rand() % $char_length;
		$password .= $chars[$num];
	}
	return $password;
}

The following line can be omitted when using PHP 4.2 or higher:

srand((double)microtime()*1000000);

The seeding of the random number generator happens automatically in later versions.

Below are some examples to demonstrate what this function can do for you.

generatePassword(); // May return: 9inhpS

generatePassword(8, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'); // May return: UYHCCZBD

generatePassword(4, '0123456789'); // May return: 2561

If you found this helpful or have any improvements I would love to hear it!

, No Comments

No comments yet.


Leave a Reply

Advertisements: