I wrote this function in response to someone else’s attempt on a forum I was asked to join. It basically generates a string of random letters and numbers with the letters being in both upper and lower case. It is easy to edit it to only use upper or lower case letters or even add symbols as well. I initially wrote it in PHP and then rewrote it in JavaScript as well.
function randomString($strLen = 32) { // Create our character arrays $chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9)); // Just to make the output even more random shuffle($chrs); // Create a holder for our string $randStr = ''; // Now loop through the desired number of characters for our string for($i=0; $i< $strLen; $i++) { $randStr .= $chrs[mt_rand(0, (count($chrs) - 1))]; } return $randStr; } |
Using it is simply a case of calling it and specifying how long to make the string otherwise it uses the default length of 32 characters.
echo randomString(12);
To also make it use symbols you just change the array_merge to
Read more »
Last Comments