Rand () PHP Function

The Rand() function generates random integers

Businesswoman working in the office
Zhang Bo/E+/Getty Images

The rand() function is used in PHP to generate a random integer. It can also be used to generate a random number within a specific range—a number between 10 and 30, for example. If no max limit is specified, the largest integer that can be returned is determined by the getrandmax() function, which varies by operating system. In the case of Windows, the largest number that can be generated is 32768.

However, you can set a specific range to include higher numbers.

Example Code for the Rand() Function in PHP

 print rand() . "<br>"; 
 //generates and prints a random number

 print rand(10, 30) . "<br>";​ 
 //generates and prints a random number between 10 and 30 (10 and 30 are included)

 print rand(1, 1000000); 
 //generates and prints a random number between on and one million

Security Concerns Using Rand() Function

The random numbers generated by this function are not cryptographically secure values, and they should not be used for cryptographic reasons. If you need secure values, use other random functions such as random_int(), openssl_random_pseudo_bytes() or random_bytes()

Note: Beginning with PHP 7.1.0, rand() is an alias of mt_rand(). The mt_rand() function is said to be four times faster and it produces a better random value. However, the numbers it generates are not cryptographically secure.

The PHP manual recommends using the  random_bytes() function for cryptographically secure integers.