Simple random text generator in PHP

Posted by Marijn Rongen on December 8, 2009 in Webdesign tips

Lately I have encountered the need for random text generators in several of my clients' projects. Applications vary from anti-spambot security codes to automatic password generating. To retain a flexible solution applicable in all those circumstances and more I have created a simple function in PHP.

The function can be called with 2 arguments, the first controlling the lenght of the output string and the second sets the allowed characters. Both of these are optional, if you call the function without arguments a six character long alphanumeric string will be generated.

function generatePassword($length = 6, 
$chars = '0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
$password = '';
$char_length = strlen($chars);
srand((double)microtime()*1000000);
for ($i = 0; $i < $length; $i++)
{
$num = rand() % $char_length;
$password .= $chars[$num];
}
return $password;
}



The following line can be omitted when using PHP 4.2 or higher:

srand((double)microtime()*1000000);


The seeding of the random number generator happens automatically in later versions.

Below are some examples to demonstrate what this function can do for you.

generatePassword(); // May return: 9inhpS

generatePassword(8, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'); // May return: UYHCCZBD

generatePassword(4, '0123456789'); // May return: 2561



If you found this helpful or have any improvements I would love to hear it!

Permalink

More from the same category:

No replies made on this article

Be the first to reply to this article, use the form below.

Reply to this article:

Your name:


Your e-mail: (not required and always hidden)


Your website url: (not required)


Copy the 4 number security code:
Security code

Your reply: