Generate a random number with PHP.

This is a short guide on how to generate a random number using PHP.

Let’s take a look at one of the simplest examples:

In the code sample above, we used PHP’s rand function to generate a random number between 0 and 10. If we wanted a number between 1 and 10, then we’d simply change our $min variable to 1, as $min represents the lowest value that the rand function should return. If we wanted a number between 1 and 100, then we’d change $min to 1 and $max to 100. Pretty simple, right?

It is important to note that the rand function is not cryptographically secure and that it should not be used in any important security features. This function will return what we call a pseudo random value. A pseudo random value isn’t really random as it is often based on things such as the current date and time.

In the next example, we will use the function mt_rand instead of rand:

The mt_rand function is superior to rand because it uses a better randomization algorithm (Mersenne Twister Random Number Generator). In the example above, we are generating a random number between 1 and 1000.

Although the mt_rand function is more “random” than the rand function, it is still not cryptographically secure! This means that you should not use it in cases where an unbiased random number is absolutely critical.

It is worth noting that the mt_rand function has completely superseded the rand function as of PHP 7.1. Since 7.1. onward, rand has become an alias of mt_rand. This means that if you call the rand function, you will really be calling the mt_rand function.

Cryptographically secure.

If you need a random number that is cryptographically secure, then you have two choices.

  • If you are using PHP 7 or above, then you can use the random_int function. This function works similar to the functions we used in the code samples above.
  • If you are using an older version of PHP, then you should check out the random_compat on Github, which provides PHP 5.x support for the random_int function.

Hopefully, this article managed to answer any questions that you had.

Related: Generate a random token with PHP.