PHP Code Snippets

Free Random String Generator Script

I wrote this script to generate a random string of random length for a captcha image. I suppose you could also use it to generate passwords but you would need to add password strength tests, encryption and use over a secured connection.

By varying the parameters passed to the function, you can generate fixed or random length strings; allow or prevent repetitions, select alpha, numeric, alphanumeric and specify upper/lower case or mixed case. You can also specify a list of characters to exclude and optionally force no character repetition.

For a captcha image, I like to use mixed alphanumeric, excluding the commonly confused characters I,l,1; 0,o,O; 5,S; 2,Z. If there is a spoken captcha option, eliminating xX, fF, sS is common.

There is nothing novel in this script - it is more of a convenience than anything. So, although it contains a copyright notice, I don't really expect anyone to keep it but I hope that if you find it useful or improve upon it, you may send me a note to let me know.

To use the script

To use, copy the function and add it to the end of your php script.

Then copy the function call that is closest to your requirements, change the variables to match your own and insert where you need it in your script.

There are no global variables so there should be no conflict with your existing script, so long as you don't have register_globals on.

Examples follow. Reload the page for new output.

Requirement

Function call

Result

Default - alphanumeric, UC and LC
UlJx8
Numeric
0931288904
Numeric,
no repeat,
random length from 5 to 8
36482570
Default,
exclude "1l0oO5S2Z"
TYU4IqbinT9N4Uk
Alpha, upper case,
exclude "1aeilou0"
VFSTKVTKNKDKGMYBHWRP
Alpha,
lower case,
exclude "1aeilou0fFsSxX"
tkfnrbfwryffvxrwrtnv
Alphanumeric,
upper and lower case
random length 10 - 20
s0f2bDzyoy0Wg7iIuHtN
Alphanumeric,
upper case
US4VBOY45NLXB7BADQX5
Alphanumeric,
lower case,
exclude "1l0oO5S2Z"
9u6igv343rgm9mhm47gt
Alphanumeric,
upper case,
exclude "1l0oO5S2Z"
No repeat characters

Becaose there are not enough unique characters to fill the string, an error Notice is issued and repeats are allowed.
SZVLQLMRTUXXXLNHZUOR
Notice: ALLOWING REPEATS - only 18 chars available in . . . jk-php-random-string-script.php on line 443