Rated an average of 4.5714 stars by 7 people

Random String Generator

Script Details:
Added on October 13, 2007 by Zhay. Last modified June 24, 2008.
Zhay accreditted the script to "Aidan Lister <aidan@php.net>."

Description:
Generate and return a random string

Tags: alpha, generate, hexadecimal, numeric, random, seed, string

Instructions:
Random alphanumeric string:

<?php
echo str_rand(15, 'alphanum');
?>

Random string from custom character list:

<?php
echo str_rand(15, '0123');
?>

Code:

<?php
# Snippet from PHP Share: http://www.phpshare.org

/** * Generate and return a random string * * The default string returned is 8 alphanumeric characters . * * The type of string returned can be changed with the "seeds" parameter . * Four types are - by default - available: alpha, numeric, alphanum and hexidec . * * If the "seeds" 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$seeds 'alphanum')
{
    
// Possible seeds
    
$seedings['alpha'] = 'abcdefghijklmnopqrstuvwqyz';
    
$seedings['numeric'] = '0123456789';
    
$seedings['alphanum'] = 'abcdefghijklmnopqrstuvwqyz0123456789';
    
$seedings['hexidec'] = '0123456789abcdef';
    
    
// Choose seed
    
    
if (isset($seedings[$seeds]))
    {
        
$seeds $seedings[$seeds];
    }
    
    
// Seed generator
    
list($usec$sec) = explode(' 'microtime());
    
$seed = (float) $sec + ((float) $usec 100000);
    
mt_srand($seed);
    
    
// Generate
    
$str ' ';
    
$seeds_count strlen($seeds);
    
    for (
$i 0$length $i$i++)
    {
        
$str .= $seeds{mt_rand(0$seeds_count 1)};
    }
    
    return 
$str;
}
?>

Review this PHP Script:

Rating:

Comments:




Comments

  • August 18, 2009
    harrykhurana Rated 5 stars
    this is very good and user full function and able to generate any kind of random number. m glad to fins this function and thanks to person who have code it
  • August 2, 2011
    thenightarcher Rated 5 stars
    Great script!Thanks!

Login

User:
Pass:

Register

Not a member? Register today and receive the many free benefits of being a member!

Advertisements