24
Jul
3
PHP – Random string generator snippet
This is a little function that I use all the time to generate random strings. There are 3 options for random strings with this: Alpha, Alpha-numeric, and Alpha-numeric with symbols. This is important because sometimes it’s a good idea not to allow special characters in a php string. However, the special characters are great if you need to create a key or initialization vector for 2 way encryption.
This can be used to generate random passwords or keys or just about anything else that needs a random string. You can also throw this directly into a class and use it as a static method.
/** * Generate a random string * * @param int $length * @param int $mode 1 = Alpha, 2 = Alpha-numeric, 3 = Alpha-numeric with symbols * @param boolian $char_set Set true for Upper and Lower case letters * @return string */ function random_string($length=16,$mode=1,$char_set=false) { $string = ''; $possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; if($char_set) { $possible .= strtolower($possible); } switch($mode) { case 3: $possible .= '`~!@#$%^&*()_-+=|}]{[":;<,>.?/'; case 2: $possible .= '0123456789'; break; } for($i=1;$i<$length;$i++) { $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); $string .= $char; } return $string; } |
Examples:
echo random_string(32); //WQTISVJVMWSEFXEIQISJPCBENFEHQAN |
echo random_string(16,2,true); //cZhVGHJb0PqJIk3 |
echo random_string(16,3); //=,:UT__GN[ST>GH |
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
Subscribe to the RSS feed and have all new posts delivered straight to you.
3 Comments:
Why not just use uniqid() for alpha numeric?
There’s no way to control length with uniqid(). Otherwise if you’re going to hash it, uniqid() should work fine.
Another good way to do it is with the chr() function using characters 33-126 and (128-255?). The problem here is that you need to use escape characters: 92 (\) and/or 34,44 (” and ‘).