DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Random Password Generator

  • submit to reddit
        This is a complete, working, random password generator for PHP. It allows the implementor to customize the character sets that the password is generated from.

To configure the generator, create the following configuration array. It is an array of arrays where each element array defines the characters in the pool and the minimum and maximum number of these characters that must appear in the result password. Each member array is given a single character token that identifies it.
// Configuration definitions, move to config.php
$CONFIG['security']['password_generator'] = array(
	"C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 4, 'maximum' => 6),
	"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 1, 'maximum' => 2),
	"N" => array('characters' => '1234567890', 'minimum' => 2, 'maximum' => 2)

The GeneratePassword() function uses the configuration array to generate a password. It starts by creating a meta-password, which is a shuffled string of the tokens from the configuration data. After the meta-password is ready, it loops through it and uses each token to choose a character from the pool of available characters defined in the configuration arrays. Once it is done, it returns the result.
function STEM_GeneratePassword()
	// Create the meta-password
	$sMetaPassword = "";
	global $CONFIG;
	$ahPasswordGenerator = $CONFIG['security']['password_generator'];
	foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
		$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
	$sMetaPassword = str_shuffle($sMetaPassword);
	// Create the real password
	$arBuffer = array();
	for ($i = 0; $i < strlen($sMetaPassword); $i ++)
		$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];

	return implode("", $arBuffer);

Version 0.1.0 - 2006-02-14
STEM: The STEM Cells of PHP
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License