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
Ri8SN
Numeric
8559005722
Numeric,
no repeat,
random length from 5 to 8
49256
Default,
exclude "1l0oO5S2Z"
XFwbjj8HphU8BdB
Alpha, upper case,
exclude "1aeilou0"
CZMRZHMVKTCKRVPTZMTS
Alpha,
lower case,
exclude "1aeilou0fFsSxX"
mzdgpzcwmtkrfsxfssns
Alphanumeric,
upper and lower case
random length 10 - 20
CSBi8Gx7x44uzGpHUtJQ
Alphanumeric,
upper case
9SRRDFZB7J9SIX55QNDK
Alphanumeric,
lower case,
exclude "1l0oO5S2Z"
m9gu4wk9tuj4rvwfnmai
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.
NWVPQJYWOJPWNHSORTRL
Notice: ALLOWING REPEATS - only 18 chars available in . . . jk-php-random-string-script.php on line 443