Random string generator
By: Daniel

Have you ever needed a random string to be created for a certain task? The below code is great for using as a random password generator, security code generator and such.

<?php
function randomstring($length = 8) {
  // $salt contains the list of available characters to use in this random string
  $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  // Start a random string
  srand((double)microtime()*1000000);
  $i = 0; // Set our length counter at 0
  while ($i < $length) { // Loop through creating our random string
    // Get the position of the random character we want
    $num = rand() % strlen($salt);
    // Use substr to extract this from our $salt above
    $tmp = substr($salt, $num, 1);
    // Add the character we got above and add to the rest of string
    $pass = $pass . $tmp;
    // Increment our length counter one
    $i++;
  }
  // We have finally reached our max length
  // Lets return the string for use in the rest of our script
  return $pass;
}
?>

To use this code you would run:

echo randomstring(8); // Produces a random 8 character long string
$rand = randomstring(8);
echo $rand;
1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading ... Loading ...

One Response to “Random string generator”

  1. Demoli Says:

    I wouldnt reccomend this function for passwords. Some basic testing shows a 14.5% collisions rate over 10,000 runs.

    For password generation you will need something with much higher entropy.

Leave a Reply

geovisitors