Generate unbreakable passwords from php

This is a short post to share my favorite way of generating strong passwords in php.

The advantage over other functions you’ll find over the internet is that it makes sure it uses all the character sets also making sure no character will repeat in the final password.

This outcome of the script is similar with what is generated in cpanel when creating new accounts/emails.

function generatePassword($length=12){
   $validchars = array();
   $validchars[] = "0123456789";
   $validchars[] = "abcdfghjkmnpqrstvwxyz";
   $validchars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $validchars[] = "_!@#$%&*()-=+/";
	
   $password  = "";
   $counter   = 0;

   shuffle($validchars);
   while ($counter < $length) {
	   foreach($validchars as $rand_key => $pool) {
			//every letter is different
			do {
				$actChar = substr($pool, rand(0, strlen($pool)-1), 1);
				if(!strstr($password, $actChar)) break;
			} while (1==1);
			$password .= $actChar;
			$counter++;
	   }
	   reset($validchars);
   }
   return $password;
}

echo generatePassword();