Versatile random string generator

A cursory glance around the web will reveal a ton of PHP-based random string generators. With enough looking you’ll find generators that do any of the following: * Strings with letters * Strings with numbers * Strings with letters and numbers * Uppercase, lowercase * Fixed, variable length strings * Option to include symbols

Problem is, none of them ever incorporated all this functionality. Every generator was a hodgepodge, e.g. some forced inclusion of numbers, or allowed either upper or lowercase, not both. All of these are great options, and it would be great to have all of them at your disposal in one tight function. No more! I got so sick of finding shortcomings that I finally just put it all together myself. The following function allows you to choose a string length, as well as the character sets to use when building your random string. You can even include a set more than once, giving greater usage weight to certain characters. Finally, complete flexibility!lang="php"> function koehl_generator($length = 10, $charsets = 'lower') {

$upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

$lower = 'abcdefghijklmnopqrstuvwxyz';

$numbers = '1234567890';

$symbols = '!@#$%^&*()-_=+<>,.?/:;[]{}|~'; if (!is_array($charsets)) $charsets = array($charsets);

$charset_pool = array();

foreach ($charsets as $set) {

$charset_pool[] = $$set;

}

$max = (sizeof($charset_pool) - 1);

$v = “;

for ($i = 0; $i < $length; $i++) {

$this_pool = $charset_pool[rand(0, $max)];

$v .= $this_pool[(rand() % strlen($this_pool))];

}

return $v;

} // usage examples

echo koehl_generator(10, ‘upper’) . ’ ’;

echo koehl_generator(10, 'lower’) . ’ ’;

echo koehl_generator(10, 'numbers’) . ’ ’;

echo koehl_generator(10, 'symbols’) . ’ ’;

echo koehl_generator(10, array('upper’, 'lower’)) . ’ ’;

// order of the array in the second argument does not matter

echo koehl_generator(15, array('lower’, 'upper’, 'numbers’)) . ’ ’;

echo koehl_generator(15, array('lower’, 'numbers’, 'upper’)) . ’ ’;

echo koehl_generator(15, array('upper’, 'lower’, 'numbers’, 'symbols’)) . ’ ’;

echo koehl_generator(15, array('lower’, 'symbols’)) . ’ ’;

// note how often letters appear in the next one

echo koehl_generator(20, array('lower’, 'lower’, 'numbers’)) . ’ ’;


Adding your own custom set is easy too. Include a new set following the syntax of the existing ones, then call your new set by variable name in the second argument...
<pre lang="php">
// add this to the top of the function...

$the_basics = 'abc123';
// then use it like so...

echo koehl_generator(5, 'the_basics') . '
';

echo koehl_generator(10, array('the_basics', 'symbols')) . '
';

If you find this useful, please be sure to give me some link love, just a reference URL to this page in your code would be fine. Using the share buttons below would be great as well!