Quick and easy random string generation
Posted on April 5th, 2004 in Code Repository | 27 Comments »
Generating a random string is an incredibly common task, this function provides quick string generation with four available output types: alpha, numeric, alphanum and hexadec.
/**
* Generate and return a random string
*
* The default string returned is 8 alphanumeric characters.
*
* The type of string returned can be changed with the output parameter.
* Four types are available: alpha, numeric, alphanum and hexadec.
*
* If the output parameter does not match one of the above, then the string
* supplied is used.
*
* @author Aidan Lister <aidan@php.net>
* @version 2.1.0
* @link http://aidanlister.com/repos/v/function.str_rand.php
* @param int $length Length of string to be generated
* @param string $seeds Seeds string should be generated from
*/
function str_rand($length = 8, $output = 'alphanum')
{
// Possible seeds
$outputs['alpha'] = 'abcdefghijklmnopqrstuvwqyz';
$outputs['numeric'] = '0123456789';
$outputs['alphanum'] = 'abcdefghijklmnopqrstuvwqyz0123456789';
$outputs['hexadec'] = '0123456789abcdef';
// Choose seed
if (isset($outputs[$output])) {
$output = $outputs[$output];
}
// Seed generator
list($usec, $sec) = explode(' ', microtime());
$seed = (float) $sec + ((float) $usec * 100000);
mt_srand($seed);
// Generate
$str = '';
$output_count = strlen($output);
for ($i = 0; $length > $i; $i++) {
$str .= $output{mt_rand(0, $output_count - 1)};
}
return $str;
}
A quick example:
// Simple echo str_rand(); // Longer echo str_rand(15); // Really big number echo str_rand(15, 'numeric'); // Custom seeds echo str_rand(15, '01');
This would produce the following output:
m2dy5ofe remdjynd47b66hq 504359393089603 111001110111101
27 Responses
Just what I needed! Thanks.
Gracias funciona realmente bien
really simple and great solution, thanks.
3 words: simple great usefull that is str_rand()
I like it , thanks
good!!! good job!! really tanks!!
Really great! Very flexible! Thanks alot!
That’s it, saves me several minutes of work, will be included to my standards class
Very cool! Saved me some work, thanks!
Thanks dood.
Thanks! I’m using it at dailybeacon.utk.edu
Perfect! Thank you
I kiss you!
Thanks a bunch!
Awsome, thanks.
We just used that little bit in our app. I didnt want to build an array of random numbers casted as string, this made things fast.
nice
Thanks, saved me some time!
Thanks much! I’m designing a mail-back registration feature for this tsunami disaster relief website I maintain. Need the number to generate random activation codes.
Very helpful. Thank you!
Thanks a lot!
I used this to fix the auto-add function of firefox and IE, for my test-program.
thanks. this is great!
klein aber oho
thx
GREAT
yeh, it’s cool.. I’m gona use it
This is great Aidan, but I think you should add A-Z to the alpha and alphanum list and add another arg which allows a user to select mix case, lower case, or upper case
Compact and useful. Keep it up
Verynice, tnx!