Code Snippet > PHP
Generate Random String with PHP
This purpose of this function is to generate a random string comprise of alphanumeric string but excludes i, l, 1, o and 0 to avoid confusion. You can use it to generate activation code or password.
PHP
Usage: you can either call getCode() - the length of the code will be 12, otherwise, you can specify the length you preferred.
function getCode($length=12) {
//Ascii Code for number, lowercase, uppercase and special characters
$no = range(48,57);
$lo = range(97,122);
$up = range(65,90);
//exclude character I, l, 1, 0, O
$eno = array(48, 49);
$elo = array(108);
$eup = array(73,79);
$no = array_diff($no,$eno);
$lo = array_diff($lo,$elo);
$up = array_diff($up,$eup);
$chr = array_merge($no, $lo, $up);
for ($i=1;$i<=$length;$i++) {
$code.= chr($chr[rand(0,count($chr)-1)]);
}
return $code;
}
This code snippet was submitted by:
Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.
Leave a comment
Have something to say? Drop a comment! No HTML tags are allowed in the comment textfield.





















0 comments