[php] Random number in range [min - max] using PHP

Is there a way to generate a random number based on a min and max?

For example, if min was 1 and max 20 it should generate any number between 1 and 20, including 1 and 20?

This question is related to php security random

The answer is


Try This one. It will generate id according to your wish.

function id()
{
 // add limit
$id_length = 20;

// add any character / digit
$alfa = "abcdefghijklmnopqrstuvwxyz1234567890";
$token = "";
for($i = 1; $i < $id_length; $i ++) {

  // generate randomly within given character/digits
  @$token .= $alfa[rand(1, strlen($alfa))];

}    
return $token;
}

rand(1,20)

Docs for PHP's rand function are here:

http://php.net/manual/en/function.rand.php

Use the srand() function to set the random number generator's seed value.


A quicker faster version would use mt_rand:

$min=1;
$max=20;
echo mt_rand($min,$max);

Source: http://www.php.net/manual/en/function.mt-rand.php.

NOTE: Your server needs to have the Math PHP module enabled for this to work. If it doesn't, bug your host to enable it, or you have to use the normal (and slower) rand().


In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.


I have bundled the answers here and made it version independent;

function generateRandom($min = 1, $max = 20) {
    if (function_exists('random_int')):
        return random_int($min, $max); // more secure
    elseif (function_exists('mt_rand')):
        return mt_rand($min, $max); // faster
    endif;
    return rand($min, $max); // old
}

(rand() % ($max-$min)) + $min

or

rand ( $min , $max )

http://php.net/manual/en/function.rand.php


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?