Call Now 407.243.8420

Generate A Random Password in PHP

The following function will generate a random password or alphanumeric string…

// usage: $newpass = createRandomPassword();
function createRandomPassword() {
	$chars = "abcdefghjkmnpqrstuvwxyz23456789";
	srand((double)microtime()*1000000);
	$i = 0;
	$pass = '' ;
	$num_chars = strlen($chars);
	while ($i <= 7) {
		$num = rand() % $num_chars;
		$tmp = substr($chars, $num, 1);
		$pass = $pass . $tmp;
		$i++;
	}
	return $pass;
}

Update: Co-location and managed hosting company OnyxLight Communications points out that it may be more secure and user-friendly to use the following for the $chars value:

$chars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%&";

Tags: , , , , ,

Leave A Comment