Generate Random String Using PHP

If you want to generate random numbers, it is possible by using PHP’s rand function. But if you want to generate random string, it is not possible by using rand function. Because rand function only returns numbers as integer between two values.  I coded a simple PHP function that works exactly same as rand function but the deference is it returns strings. You can use it in captcha function, random password generator or anywhere else.



randString Function
/**
* Random String Generator
*
* @param optional int $min
* @param optional int $max
*
* @return string
*/

function randString($min = 5, $max = 8){
	# get random character length between minimum and maximum length
	$length = rand($min, $max);
	$string = '';
	# character index [0-9a-zA-Z]
	$index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	# loop random times defined by $length
	for ($i=0; $i < $length; $i++) {
		# get random character index
		$string .= $index[rand(0, strlen($index) -1)];
	}
	return $string;
}

Usage
echo randString(4, 8);

Output
NO2xDPR

Tips: You can remove vowel (a, e, i, o, u) from index. It will help to generate meaningless string and prevent from bad words (like f**k). Also you can add some special characters (like @, #, $, % & ...). It helps to generate strong password.

No comments:

Post a Comment