Password Creator

November 28, 2009

Having a secure password is essential to the security of you computer, and your data online. Weak passwords can be broken surprisingly easily, leading to massive data breaches and headaches for companies.

Awhile ago, I created a simple function that would generate a string of random characters, essentially making it a password generator. Since I relaunched me site, however, it disappeared. I made a few tweaks to it, and have re-released it on my new site.

The code behind how it works is actually extremely simple–all you have to do is create a string with all the characters you want to be available in the password, and then select characters at random passwords in that string.

Example code:

function randomCharString($length = 8) {
	$length = intval($length);

	$chars = array_merge(range(0, 9), range("A", "Z"));
	$chars = implode("", $chars);

	$output = '';
	while($length-- > 0) {
		$output .= $chars{rand(0, strlen($chars) - 1)};
	}

	return $output;
}

You can customize what kinds of passwords are created by changing the $chars array/string. For example, to create passwords that use uppercase letters and numbers, but not any characters that can cause confusion (O or 0, 1 or I), you could to this: $chars = 'ABCDEFGHJKLMNPQRSTUVWXY3456789';

I’ve even got plans to make some more complicated (human readable, but secure) passwords in the future.