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;
3 Votes | Average: 5 out of 53 Votes | Average: 5 out of 53 Votes | Average: 5 out of 53 Votes | Average: 5 out of 53 Votes | Average: 5 out of 5 (3 votes, average: 5 out of 5)
Loading ... Loading ...
del.icio.us:Random string generator digg:Random string generator spurl:Random string generator wists:Random string generator simpy:Random string generator newsvine:Random string generator blinklist:Random string generator furl:Random string generator reddit:Random string generator fark:Random string generator blogmarks:Random string generator Y!:Random string generator smarking:Random string generator magnolia:Random string generator segnalo:Random string generator

Leave a Reply

eXTReMe Tracker
geovisitors