Random password generator in PHP

When you want a random password you might think that for instance uniquid() is a good fit. It’s not though as it will only return hex characters.

However, using array_rand() and range() we can make for a pretty good solution:

function randCode($length = 5){
	$ranges = array(range('a', 'z'), range('A', 'Z'), range(1, 9));
	$code = '';
	for($i = 0; $i < $length; $i++){
		$rkey = array_rand($ranges);
		$vkey = array_rand($ranges[$rkey]);
		$code .= $ranges[$rkey][$vkey];
	return $code;

The idea here is to mix, A-Z, a-z and 1-9. I’m leaving zero out of it to avoid confusion between it and O.

As you can see array_rand will return a random key from the array that you then can use to get at the value.

First we pick a key for a random range (A-Z, a-z or 1-9) in $rkey. Then we pick a random key from that range in $vkey, finally we use the keys to get at a random value which we concatenate on the code/password string.

Related Posts

Tags: , ,