Hi all! In this article, we'll look at what's new for random number generation in PHP 7.1.

This update happened invisible to developers, but improved the language PHP programming in the field of random number generation.

As far as we know, in PHP we can use the rand(min, max) function to generate random numbers:

Echo rand(7, 17);

If you now refresh the page, you will receive a new random number each time.

But not everything is as simple as it might seem. The point is that depending on what you are generating the random number for, the rand() function uses different systems generation. Those. it depends on the system in which it is used. Some systems may use weak generation methods, so you will receive numbers that are not entirely random.

In PHP 7.1 this problem was fixed and the mt_rand() function was added:

Echo mt_rand(7, 17);

This feature works much better, including security. What's also important to know is that if you use the rand() function in PHP 7.1, it will automatically be overwritten by mt_rand() . Those. rand() is now just an alias for mt_rand() .

Many other functions for generating random results have been improved in PHP 7.1. For example, let's look at how we can get a random value from an array:

$names = ["Ivan", "Alexander", "Vasiliy"];
echo $names;

Those. any functions such as this have been improved to produce better random numbers in PHP 7.1. Yes, this update went unnoticed, but no matter what language you write in, it is very important to understand what is happening inside a function and how it behaves.

Task
You need to generate a random number within a numeric range.

Solution
The mt_rand() function is designed for this:

// random number between $upper and $lower, inclusive
$random_number = mt_rand($lower, $upper);

Discussion
Random number generation is useful when you need to display a random picture on the screen, randomly assign a starting point in a game, select a random entry from a database, or generate a unique session identifier. In order to generate a random number in the interval between two points, you need to pass two arguments to the mt_rand() function:

$random_number = mt_rand(1, 100);

Calling mt_rand() with no arguments returns a number between zero and the maximum random number returned by mt_getrandmax(). It is difficult for a computer to generate a truly random number. He is much better at following instructions methodically and is not so good if he is required to act spontaneously. If you need to force a computer to produce a random number, then you need to give it a certain set of repeatable commands, and the very fact of repeatability makes achieving randomness less likely.

PHP has two different random number generators: the classic function called rand() and the more advanced function mt_rand().

MT (Mersenne Twister) is a pseudo-random number generator named after the French monk and mathematician Marin Mersenne, who studied prime numbers. The algorithm of this generator is based on these prime numbers. The mt_rand() function is faster than the rand() function and produces more random numbers, so we prefer the former.

If you have PHP version earlier than 4.2, then before calling the mt_rand() (or rand()) function for the first time, you need to initialize the generator with an initial value by calling the mt_srand() (or srand()) function. The seed is the number that the random function uses as the basis for generating the random numbers it returns; it refers to a way to resolve the dilemma mentioned above – repeatability versus randomness.

As an initial value that changes very quickly and with a low probability of repeatability (these properties should be characterized by a good initial value), you can take the value returned by the high-precision time function microtime(). It is enough to initialize the generator once. PHP 4.2 and later automatically handles initialization, but if the initial value is set manually before the first call to mt_rand(), PHP does not replace it with its own initial value.

If you need to select a random record from a database, the easiest way is to first determine the total number of fields in the table, select a random number from that range, and then query that row from the database:

$sth = $dbh->query("SELECT COUNT(*) AS count FROM quotes");
if ($row = $sth->fetchRow()) (
$count = $row;
) else (
die ($row->getMessage());
}
$random = mt_rand(0, $count - 1);
$sth = $dbh->query("SELECT quote FROM quotes LIMIT $random,1");
while ($row = $sth->fetchRow()) (
print $row .

"\n";
}

This code snippet determines the total number of rows in the table, generates a random number from that range, and then uses LIMIT $random,1 to SELECT one row from the table starting at position $random. In MySQL version 3.23 or higher, an alternative option is possible:

$sth = $dbh->query("SELECT quote FROM quotes ORDER BY RAND() LIMIT 1");
while ($row = $sth->fetchRow()) (
print $row . "\n";
}

In this case, MySQL first randomizes the rows and then returns the first row.

Now we take a ready-made password generation function and write a script to recover or create a new password for users of your site.

Password recovery script

How is the script usually written?

As always, a step-by-step scheme is drawn up, what we must do step by step. Everything happens in one file, reminder.php

1. We run the script only if there is a certain variable, for example $action;

2. To start the password generation process, the user specifies email address$_POST[`ema‘l`]; To simplify the code, let's assign given value variable $email.

3. Check using regular expressions All symbols ensure that the user has entered the correct email address. If not, we display an error and stop the script. If everything is correct, we move on.

4. We search in the database, in our case in the table user's users with the same postal address. If not, we issue an error that there is no such address in the database and stop the script.

5. There is a user with this address in the database, go ahead and launch the function of generating a new password. Also, using the email address, we get the user’s unique id from the database and write it to the $id variable;

Initializes the random number generator. Syntax:

Void srand(int seed)

Initializes the random number generator with the seed value.

Srand((double) microtime()*1000000);
$random = rand();
echo $random;

GETRANDMAX

Returns the largest possible random number. Syntax:

Int getrandmax()

This function returns the maximum value that can be obtained using the rand() random number generation function.

Usually it is 32767

Generates a random number. Syntax:

Int rand()

When called with the optional min and max parameters, this function generates a random number up to and including those parameters. If the min and max parameters are missing, a number ranging from 0 to RAND_MAX is returned.

For this function to work correctly, before using it, you need to initialize the random number generator with the srand() function.

lcg_value()

LCG pseudo-random number generator (PHP 4, PHP 5)

Description:

Float lcg_value (void)

lcg_value() returns a pseudorandom number in the range (0, 1). The function combines two generators with 2^31 - 85 and 2^31 - 249 in a period.

mt_getrandmax()

Shows the largest possible random value (PHP 3 >= 3.0.6, PHP 4, PHP 5)

Description:

Int mt_getrandmax (void)

Shows the maximum value that can be returned by mt_rand()

mt_rand()

Generates the best random value (PHP 3 >= 3.0.6, PHP 4, PHP 5)

Description:

int mt_rand()

Many older versions of random number generators have questionable characteristics and are slow. By default, PHP uses the rand() function to generate random numbers. The mt_rand() function is a good replacement. It uses a random number generator that is 4 times faster than rand() and uses Mersenne Twister.

Called without the optional min and max arguments, mt_rand() returns a pseudo-random value ranging between 0 and RAND_MAX. If you need to get, for example, random values ​​between 5 and 15 inclusive, look for mt_rand (5, 15).

Example of using mt_rand()

The result of running this example will be something like this:

1604716014
1478613278
6

Comment

Note: In versions prior to 3.0.7, the second parameter of the function specified the range of numbers. For example, to obtain random numbers between 5 and 15 in these versions you need to specify the mt_rand(5, 11) function.

mt_srand()

Sets the initial value of the best random number generator (PHP 3 >= 3.0.6, PHP 4, PHP 5)

Description:

Void mt_srand()

Sets the initial value of the random number generator using seed. As of PHP 4.2.0, seed is optional and the default settings for random values ​​are omitted.

Example of using mt_srand()

Note: As of PHP 4.2.0, it is no longer necessary to initialize the random number generator with srand() or mt_srand(), since this is now done automatically.

Technically, the term "random number generator" is nonsense, since numbers themselves are not random. For example, is 100 a random number? What about 25? What this term actually means is that it creates a sequence of numbers that appear randomly. This raises a more difficult question: what is a sequence of random numbers? The only correct answer: a sequence of random numbers is a sequence in which all elements are unrelated. This definition leads to the paradox that any sequence can be either random or non-random, depending on how the sequence is obtained. For example, the following string of numbers
1 2 3 4 5 6 7 8 9 0
was obtained by typing the top line of the keyboard in order, so the sequence cannot be considered randomly generated. But what if you get the same sequence when you take the numbered tennis balls out of the barrel. In this case, it is already a randomly generated sequence. This example shows that the randomness of a sequence depends on how it was obtained, not on itself.

Remember that a computer-generated sequence of numbers is deterministic: each number except the first one depends on the numbers before it. Technically, this means that only a quasi-random sequence of numbers can be generated by a computer, i.e. in fact they are not truly random. However, this is sufficient for most tasks and for simplicity such sequences will be called random. One very interesting method was developed by John von Neumann; it is often called root mean square. In this method, the previous random number is squared, and then the middle digits are extracted from the result. For example, if you are creating numbers with three digits, and the previous number was 121, then squaring it gives the result 14641. Isolating the middle three digits gives the next random number 464. The disadvantage of this method is that it has a very short repetition period, called a cycle . For this reason this method not used today. Modern methods of generating random numbers are much more complex.

Random numbers in PHP

PHP has two groups of functions for working with random numbers. Purely externally, they can be distinguished by the mt_ prefix for all functions of one of the groups.

Deprecated features
rand function Returns an integer between zero and the value of RAND_MAX (which is 32767). Can have two optional integer parameters - if they are specified, a random number is generated from the first parameter to the second.

Echo rand(); echo rand(1,100); // Give out a random number from 1 to 100

Function srand. Specifies the sequence of random numbers produced by the rand function. Has a whole parameter - when different meanings With this parameter, rand will produce different sequences of numbers. The srand function only needs to be called once before all calls to the rand function. Usage example:

Srand(1288); // Initialize the random number generator for($i=0; $i