Generate random strings using PHP

July 19, 2014 | Last tested: June 2015 | 846 views | Comments

Use the range() function to set up the strings and the function shuffle() to mix up the position of the created array that contains the range of element strings. Join the shuffled array elements with a string using the function implode(), then get the desired number of strings with substr(). Finally, randomly shuffle the selected string using the function str_shuffle().

For Example.

Randomly generate an eight character string.

Note: This is not recommended for generating random passwords.

For generating passwords, read Generate Random Passwords in PHP instead.

$string = array_merge(range('a','z'),range('A','Z'),range(0,9));
shuffle($string);
echo str_shuffle(substr(implode('',$string),0,8));
//sample result
//BCO2cuJe

 

Limitations:

  1. Can only generate up to 62 characters.
  2. A string cannot be repeated (unique per generate).

 

Put it in a function

function generateRandomStrings($length){
	$string = array_merge(range('a','z'),range('A','Z'),range(0,9));
	shuffle($string);
	return str_shuffle(substr(implode('',$string),0,$length));
}

echo generateRandomStrings(8);
//sample result
//Th76UQPp

 

Related Tutorials


Must Read