Generate Random Passwords in PHP

July 26, 2014 | Last tested: June 2015 | 1924 views | Comments

Having special characters on a generated password is a must because it provides more difficulty to predict. To begin, manually put the selected special characters on a variable. Then set up the alphanumeric strings (a-z, A-Z, and 0-9) using the range() function. For position reordering, shuffle strings using the function str_shuffle(), for arrays, use the shuffle() function.

Half of the desired password strings length here are special characters, this is computed and can be easily changed using some mathematical functions like ceil() and floor().

For example.

Generate an eight character password.

Notes: This can only generate up to 94 characters, and the suggested maximum password length is usually about 16, therefore this won't be a concern. Duplicate strings can't be generated as well, but can be easily adjusted depending on the requirement.

function generatePassword($length){
	$specialString = str_shuffle('`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|');
	$string = array_merge(range('a','z'),range('A','Z'),range(0,9));

	return htmlspecialchars(str_shuffle(str_shuffle(substr($specialString,0,(floor($length/2)))) . str_shuffle(substr(implode('',$string),0,(ceil($length/2))))));

echo generatePassword(8);
//sample result


Possible developments:

Add the possibility of duplicating a String.

  • Change this line:
    $string = array_merge(range('a','z'),range('A','Z'),range(0,9));
  • To this:
    $string = array_merge(range('a','z'),range('A','Z'),range(0,9),range('a','z'),range('A','Z'),range(0,9));
  • Sample result: 7\]BU&B~


Add the possibility of duplicating a Special String.

  • Change this line:
    $specialString = str_shuffle('`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|');
  • To this:
    $specialString = str_shuffle('`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|') . str_shuffle('`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|');
  • Sample result: ]]W&uX+r


Related Tutorials

Must Read