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.
well, I was looking for a solution, and I kindda used @Chad Birch's solution merged with @Gumbo's one. This is what I came up with:
I think comments are pretty much unnecesary since the answers I used to build up this one are already thoroughly commented. Cheers!
Joining characters at the end should be more efficient that repeated string concatenation.
Edit #1: Added option to avoid character repetition.
Edit #2: Throws exception to avoid getting into infinite loop if $norepeat is selected and $len is greater than the charset to pick from.
Edit #3: Uses array keys to store picked random characters when $norepeat is selected, as associative array key lookup is faster than linearly searching the array.
This builds on Gumbo's solution by adding functionality to list a set of characters to be skipped in the base character set. The random string selects characters from
$base_charset
which do not also appear in$skip_charset
.Here are some usage examples. The first two examples use the default value for
$base_charset
. The last example explicitly defines$base_charset
.What do you need a random string for?
Is this going to be used for anything remotely analogous to a password?
If your random string requires any security properties at all, you should use PHP 7's
random_int()
function instead of all the insecuremt_rand()
answers in this thread.If you aren't on PHP 7 yet (which is probably the case, as it hasn't been released as of this writing), then you'll want paragonie/random_compat, which is a userland implementation of
random_bytes()
andrandom_int()
for PHP 5 projects.For security contexts, always use
random_int()
, notrand()
,mt_rand()
, etc. See ircmaxell's answer as well.So, let me start off by saying USE A LIBRARY. Many exist:
The core of the problem is almost every answer in this page is susceptible to attack.
mt_rand()
,rand()
,lcg_value()
anduniqid()
are all vulnerable to attack.A good system will use
/dev/urandom
from the filesystem, ormcrypt_create_iv()
(withMCRYPT_DEV_URANDOM
) oropenssl_pseudo_random_bytes()
. Which all of the above do. PHP 7 will come with two new functionsrandom_bytes($len)
andrandom_int($min, $max)
that are also safe.Be aware that most of those functions (except
random_int()
) return "raw strings" meaning they can contain any ASCII character from0 - 255
. If you want a printable string, I'd suggest running the result throughbase64_encode()
.