Computers Windows Internet

Generate random numbers within a range. PHP random function application php best random number generator

Initializes the generator random numbers... Syntax:

Void srand (int seed)

Initializes the random number generator with seed.

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 random number generation function rand ().

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 within these parameters, inclusive. If the min and max parameters are missing, a number between 0 and RAND_MAX is returned.

For correct work this function, 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 pseudo-random 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 the mt_rand () function

mt_rand ()

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

Description:

Int mt_rand ()

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

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

Example of using mt_rand ()

echo mt_rand (). "\ n";
echo mt_rand (). "\ n";

echo mt_rand (5, 15);
?>

This example will result in something like this:

1604716014
1478613278
6

Comment

Comment: Prior to 3.0.7, the second parameter of the function specified a range of numbers. For example, to get random numbers between 5 and 15, these versions require the mt_rand (5, 11) function to be specified.

mt_srand ()

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

Description:

Void mt_srand ()

Sets the seed for 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 using mt_srand ()

// seed with microseconds
function make_seed ()
{
list ($ usec, $ sec) = explode ("", microtime ());
return (float) $ sec + ((float) $ usec * 100000);
}
mt_srand (make_seed ());
$ randval = mt_rand ();
?>

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

You can use PHP's rand () or mt_rand () function to generate a random number. The requirement to use random numbers often arises in practice for naming variables, files, creating key information, and ensuring security.

Randomness and uniqueness

PHP's random function comes in two flavors: rand () and mt_rand (). It is believed that the algorithm in the first case is simpler and generates pseudo-random numbers. The second option has a faster algorithm and known mathematical characteristics... In most cases, when you need to get a random number, you can use a series of PHP random calls and get a unique combination of numbers.

If you take the numbers from 1 to 26 or from 1 to 32 as a basis and get them randomly, you can form key information as a sequence of Latin or Cyrillic letters. In this case, PHP random is a way of generating a sequence of alphabetical information, for example, for testing communication channels or algorithms.

A random number is rarely unique, since it can appear multiple times according to the distribution law of a random variable. But if we combine, in particular, the static PHP variable& Math.random of JavaScript, you can get a real unique random number that will not repeat over time.

Using the time function

The function of time, both PHP and JavaScript, allows you to form unique combinations of numbers, rarely when a sufficiently large number of events can occur at one point in time and random value will be repeated.

By applying PHP random over a range of seconds or milliseconds over a wide range of possible values, you can get unique random combinations of numbers or letters. What else?

Combining the value of the time function, a sequentially growing number and PHP random, or you can ensure reliable security of the client and server communication channels, create unique codes for variables, generate unpredictable events in algorithms.

The PHP random number generator is an excellent solution for most tasks, especially when you need to quickly get high-quality results with minimal costs. Using the rand () and mt_rand functions in conjunction with sequentially growing series of numbers or time values ​​allows you to get random numbers, both repeating in value and unique.

Hello everyone! In this article, we will look at what's new for generating random numbers in PHP 7.1.

This update happened invisibly to developers, but improved the programming language PHP in the field of generating random numbers.

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

Echo rand (7, 17);

If you refresh the page now, 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 function rand () uses different systems generation. Those. it depends on the system in which it is used. Some systems can use weak methods of generation, respectively, you will receive not entirely random numbers.

V PHP 7.1 this issue has been fixed and the function has been added mt_rand ():

Echo mt_rand (7, 17);

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

Many other functions for obtaining random results have been improved in PHP 7.1... For example, let's see 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 quality 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 happens inside a function and how it behaves.

And now we take the ready-made password generation function and write a script to restore or create a new password for your site users.

Password recovery script

How is a script usually written?

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

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

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

3. We check with the help of regular expressions all the characters so that the user correctly specified the email address. If not, display an error and terminate the script. If everything is correct, let's move on.

4. We are looking for in the database, in our case in the users table for a user with the following postal address... If not, we issue an error that there is no such address in the database, and terminate the script.

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

Technically, the term "random number generator" is absurd, since the numbers themselves are not random. For example, is 100 a random number? And 25? What this term really means is that it creates a sequence of numbers that appear randomly. This breeds more complex issue: 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 such a paradox that any sequence can be both random and non-random, depending on how this sequence is obtained. For example, the following line of numbers
1 2 3 4 5 6 7 8 9 0
was received by printing top line keyboards in order, so the sequence cannot be considered randomly generated. But what if you get the same consistency by taking the numbered tennis balls out of the keg. 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, and not on itself.

Remember that the sequence of numbers generated by the computer is deterministic: every number except the first depends on the preceding numbers. 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 such sequences will be called random for simplicity. One very interesting method was developed by John von Neumann; it is often referred to as 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 create numbers with three digits and the previous number was 121, then squaring gives 14641. Selecting 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 loop ... For this reason, this method is not used today. Modern methods generating random numbers is much more difficult.

Random numbers in PHP

PHP has two groups of random number functions. Outwardly, they can be distinguished by the mt_ prefix for all functions of one of the groups.

Deprecated functions
The rand. Returns an integer from zero to RAND_MAX (which is 32767). It can have two optional integer parameters - if they are specified, then 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

Srand. Specifies the sequence of random numbers produced by the rand function. Has an integer parameter - for different values ​​of this parameter, rand will produce different sequences of numbers. Srand only needs to be called once before all calls to rand. Usage example:

Srand (1288); // Initialize the random number generator for ($ i = 0; $ i<5;$i++){ echo rand(); echo "
"; }

Attention! As of PHP 4.2.0, you don't need to call srand () - PHP does this automatically.
Getrandmax () function. Returns the maximum random number (32767).

Functions of the second group (with the mt_ prefix)
Their names and actions are similar to the functions of the first group - mt_rand, mt_srand and mt_getrandmax. The main difference is that random numbers are taken from a wider range: from 0 to 21937 - 1. Moreover, these functions work much faster than their old counterparts, since they use the Mersenne Twister random number generator, developed in 1997 by Japanese scientists. Hence the prefix mt_ (Mersenne Twister).
Usage example:

// Give a random number from 1000 to 2000 echo mt_rand (1000, 2000);

Random numbers in JavaScript

Random number in JavaScript can be generated using Math.random (). However, it will be a fractional number between 0 and 1 (not including 0 and 1). To generate a random integer in the desired range, you need to write your own function