How to generate random string in PHP
How to generate random string in PHP
Have you ever needed to generate a random password from a given set of chars in PHP? You could also probably wanted a password salt used for encrypting the user password. Well here are two solutions which I can think of at the moment to help you generate the random string in php.
1st solution (php native)
The first solution is by using the str_shuffle() function, the same as shuffle() which I’ve showed you how to suffle an array when choosing a random background image, you would use this function on a specific string to shuffle its characters..
(PHP 4 >= 4.3.0, PHP 5)
str_shuffle — Randomly shuffles a string
1 2 3 4 5 |
function generateRandomString($length = 10) { return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); } echo generateRandomString(); |
You can of course use the function directly without creating your own function for this, but for the sake of this being more easily used in different cases, this how you do it.
Output
The output would look similar to:
1 |
J6WD2Kf1BS |
Of course you can control the length you need if you change $length to a different value.
2nd solution (implemented)
The second solution is by generating the random string manually. The same with a length set specific to 10.
1 2 3 4 5 6 7 8 9 10 |
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } echo generateRandomString(); |
Output
1 |
N5MJ6EPfDP |
There are probably other ways to do this, but for now, these two solutions should suffice. But if you’re looking in generating random strings for passwords, you should probably also check our article on hash encryption method in php.