I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:
Original string, 9 chars
$string = 'abcdefghi';
Example random string limiting to 6 chars
$string = 'ibfeca';
UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.
UPDATE: The function should generate any amount of chars as required.
Please comment the parts if you reply.
A better and updated version of @taskamiski's excellent answer:
Better version, using
mt_rand()
instead ofrand()
:Even better, for longer strings, using the
hash()
function that allows to select hashing algorithmns:If you want to cut the result down to let's say 50 chars, do it like this:
This will work only in UNIX environment where PHP is compiled with
mcrypt
.I think I will add my contribution here as well.
Thanks
you could make an array of characters then use rand() to pick a letter from the array and added it to a string.
*note that this does allow repeat characters
Most aspects of this have already been discussed, but i'd recommend a slight update: If you are using this for retail usage, I would avoid the domain ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
and instead use: ABCDEFGHJKMNPQRSTUVWXY3456789
Granted, you end up with far fewer characters, but it saves a great deal of hassle, as customers cannot mistake 0 for O, or 1 for l or 2 for Z. Also, you can do an UPPER on the input and customers can then enter upper or lower case letters -- that is also sometimes confusing since they can look similar.
this will generate random string