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.
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;




















December 8th, 2009 at 4:56 pm
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.