PHP function that generates a random string

This function is based on Jeremy Ruten’s and Earlz’s idea to first create an array of all the valid characters that can appear in the string, and then simply select a random character from that array $length times. I’ve encapsulated their code into a function so that you can use it more easily in your projects.
function generate_random_string($length)
{
	// alphanumeric random string generation based on idea by Jeremy Ruten and Earlz
	// http://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings
	// License: CC BY-SA 3.0
	
	// Made into a function by Dan Barbulescu
	// License: CC BY-SA 3.0
	
	$characters = array_merge(range('a','z'),range('A','Z'),range('1','9'));
	$characters_max_position = count($characters) - 1;
	$string = '';
	for ($i = 0; $i < $length; $i++)
	{
		$string .= $characters[rand(0,$characters_max_position)];
	}
	return $string;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close