In PHP how to calculate a random number?

Asked

Viewed 2,442 times

22

How to calculate a random integer between 1 and 2000 using PHP, to make a draw?

function random() {
  // codigo
}

4 answers

13


  • I was going to suggest Rand() but this one was a really good surprise. I didn’t know.

  • It is, according to official documentation, is the "improved version"

  • +1 The right answer as long as the results are not intended to be used for security purposes (example: encryption)

8

The functions mt_rand() and Rand() generate numbers pseudo-random, the numbers generated by these functions are foreseeable.

Alternatively you can make use of the function openssl_random_pseudo_bytes() (English):

Generates a string of pseudo-Random bytes, with the number of bytes determined by the length Parameter.

That translated:

Generates a pseudo-random sequence of bytes, with the number of bytes to be determined by the parameter of length.

Example

<?php
function random($min, $max) {
    $range = $min - ($max + 1);
    if($range === 0) {
        return $min;
    }
    $len = (int)(log(abs($range), 2) / 8) + 1;
    $num = hexdec(bin2hex(openssl_random_pseudo_bytes($len)));
    return ($min + ($num % $range));
}
  • 1

    Just out of curiosity, in this line of alternatives to pseudo-random there is this online service http://www.random.org/ that generates random numbers from atmospheric noise (in theory, thus generating a "true random"). Particularly I never needed to use it (in general pseudo-random is enough for common problems), but it looks cool - it has a free but limited HTTP API in number of daily calls or something like that.

  • 1

    The use of % applied to $range makes me nervous. If the maximum value $num + 1 may have is not a multiple of $range, then there are numbers more likely to appear than others (specifically smaller numbers).

  • 3

    @Luizvieira Sounds like a good idea, but be careful: HTTP doesn’t hide traffic. An attacker could use a man-in-the-Middle to predict - or even alter - the results of the draw. For better results, it should be combined with other random number sources.

  • @luiscubal Very well noted. :)

  • 1

    @Luizvieira On linux you can use the contents of /dev/urandom to generate random numbers based on aphmospheric rusts: file_get_contents('/dev/urandom', false, null, 0, $len); Or mcrypt_create_iv: mcrypt_create_iv($len, MCRYPT_DEV_URANDOM);

  • @Wynn Great info! I didn’t know about this use of noise collected from devices, thanks! By the way, looking at Wikipedia it seems that there are alternatives if you are using other Oses (like Windows, for example): http://en.wikipedia.org/wiki//dev/Random#Other_operating_systems

  • 1

    To the interested reader, beware of confusion of terms. Atmospheric noise is the noise captured by electronic circuits (such as transistor with open collector), and other means of electrical fluctuation detection. AMBIENT noise in the case of many generators used in pc may refer to digital information collected in device drivers (logical environment, not physical), being obtained by software, without specialized electronics (such as the /dev/urandom mentioned). (mouse movement, network traffic, etc.) - Both can be used in random generators, but do not use the same principles.

Show 2 more comments

2

The best option, in PHP 7 (or higher), is to use random_int:

random_int($menor_numero , $maior_numero);

Both $menor_numero and $maior_numero include themselves, so use:

random_int(0 , 1);

Will generate the number 1 or 0. In your case, use random_int(1, 2000), since it wants something between 1 (including 1) and 2000 (including 2000).


The minimum and maximum limit is defined by the constant: PHP_INT_MIN and PHP_INT_MAX, which varies according to the platform.


The random_int is "cryptographically secure", unlike the mt_rand or rand.

0

You can use the function Rand() which by defection generates a random integer.

The syntax is

rand($MenorNumeroDesejado, $MaiorNumeroDesejado)
  • 2

    Make your answer more complete, explain how the function works and enter a reference comment to the documentation of [tag:php].

  • I improved your answer to give example. You can always click edit and improve. The better the answer the more useful and more score you will receive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.