Random number generator in PHP


My daily cup of tea

Used this random number generation to generate random alpha-numeric strings:

function generate_random_string($name_length = 8) {
	$alpha_numeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	return substr(str_shuffle($alpha_numeric), 0, $name_length);
}

Alternatively, use this function in case you need to have at least lower/upper case, numeral and special characters

function generate_random_string() {
        $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $numeric = '0123456789';
        $spcl = '#@!$%';
        $rdm = substr(str_shuffle($alpha), 0, 2).substr(str_shuffle($numeric), 0, 1).substr(str_shuffle($alpha), 0, 2).substr(str_shuffle($spcl), 0, 1).substr(str_shuffle($alpha), 0, 2);
        return $rdm;
}

After some testing, I noticed that the above function repeats the patterns more often. But using mt_rand function rather than str_shuffle does a better job of shuffling around the characters. Suggest using the following function instead:

function createRandomHex($length) {
  $hex_chars = '012AB34CD56EF789';
  $string = '';
  for ($p = 0; $p < $length; $p++) {
      $string .= $hex_chars[mt_rand(0, strlen($hex_chars)-1)];
  }
  return $string;
}

View original post

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s