Generate random string
By: Daniel

Have you ever needed to create a random string for use in a project but did not understand how it is done? With the following function you will be able to create random strings of numbers, letters and letters/numbers/symbols at any length.

<?php
function randomString($length = '8', $type = '') {
  // Select which type of characters you want in your random string
  switch($type) {
    case 'num':
      // Use only numbers
      $salt = '1234567890';
      break;
    case 'lower':
      // Use only lowercase letters
      $salt = 'abcdefghijklmnopqrstuvwxyz';
      break;
    case 'upper':
      // Use only uppercase letters
      $salt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      break;
    default:
      // Use uppercase, lowercase, numbers, and symbols
      $salt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890$*#@!?';
      break;
  }
  $rand = '';
  $i = 0;
  while ($i < $length) { // Loop until you have met the length
    $num = rand() % strlen($salt);
    $tmp = substr($salt, $num, 1);
    $rand = $rand . $tmp;
    $i++;
  }
  return $rand; // Return the random string
}
?>

Some examples on how to use this would be:

<?php
echo 'Random 8 character lowercase, uppercase, numbers and symbol string: <strong>'.randomString('8').'</strong><br />';
echo 'Random 12 numbers: <strong>'.randomString('12', 'num').'</strong><br />';
echo 'Random 10 character lowercase string: <strong>'.randomString('10', 'lower').'</strong>';
?>

This would produce:

Random 8 character lowercase, uppercase, numbers and symbol string: tGPQNS0U
Random 12 numbers: 416387690323
Random 10 character lowercase string: pknqxkjsxa

To modify this code you can add extra case sections to modify what characters are added to the random string.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

Leave a Reply

geovisitors