Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.
random_int(100000, 999999)
Note that here we use random_int
, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes
was also introduced in PHP 7 and likewise uses a cryptographic random generator.
Many other solutions for random value generation, including those involving time()
, microtime()
, uniqid()
, rand()
, mt_rand()
, str_shuffle()
, and array_rand()
, are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int
or random_bytes
rather than rand()
, mt_rand()
, str_shuffle()
, etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?
I also list other things to keep in mind when generating unique identifiers, especially random ones.