Generate Random String or Password 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 string. You can use it in image 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 vowels (a, e, i, o, u) from alphabet index. It will help to generate meaningless string and it will also help to prevent from bad words. Also you can add some special characters (like @, #, $, % & ...). It help to generate strong password.

3 comments:

Go to top