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
Vt7Lc
Numeric
8381501160
Numeric,
no repeat,
random length from 5 to 8
071928
Default,
exclude "1l0oO5S2Z"
Qb3rG8ewE6qhIuh
Alpha, upper case,
exclude "1aeilou0"
SZGXPFDQTQNHZCNMYTTQ
Alpha,
lower case,
exclude "1aeilou0fFsSxX"
pywyrxzngdrshpmryjyv
Alphanumeric,
upper and lower case
random length 10 - 20
DHB1j1CFjloxXt8ryFCS
Alphanumeric,
upper case
FQMA0VZXC154722CFU14
Alphanumeric,
lower case,
exclude "1l0oO5S2Z"
midac4cxk43r43tuixt7
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.
SOQVWOLJJZTKLZLUQTVO
Notice: ALLOWING REPEATS - only 18 chars available in . . . jk-php-random-string-script.php on line 443