Php Random String

Admin   PHP   116  2021-01-14 15:48:13

Let me begin this article by saying that almost no events are truly random. Even the theoretical outcome of the classic coin toss can be predicted if we know the effects of all relevant factors, such as air friction, gravity, and initial force.

Generating random strings of letters and numbers has a similar principle. The best thing to expect is to generate numbers and strings that do not follow a pattern and would be practically impossible to guess by an attacker.

In this tutorial, we will cover different techniques for generating random numbers and literal strings in PHP. Some of them will be encrypted, while others are just for general needs, like assigning a pseudo-random filename or generating a URL and suggesting a username.

PHP RANDOME STRING

Generate random numbers in PHP

There are three different functions for generating random numbers in PHP. All of those functions will take a minimum and maximum possible value for random numbers and return a random number for you. That is rand($min, $max), mt_rand($min, $max) and random_int($min, $max).

With rand(), the minimum and maximum values ​​of integers (integers) you can create are between 0and the value returned by getrandmax(). Before PHP 7.1.0, the function was about four times slower mt_rand(). However, starting with PHP 7.1.0, it became an alias of mt_rand(). However, unlike mt_rand(), you can set the value of $maxlower $minwithout causing an error.

With mt_rand(), the minimum and maximum values ​​of integers you can create are between 0and the value returned by mt_getrandmax(). It relies on the implementation of Mersenne Twister for generating random numbers. Looks out, even though before PHP 7.1.0, this function implemented an incorrect version of the algorithm for generating numbers. However, this function has been fixed in newer versions.

This function gets even better in PHP 7.2.0 by eliminating the modulo error. This means that for some specific seed your string of random numbers should now be slightly better than older versions. Although some dedicated code can count on this trend. If so, you can use the older seed algorithm by calling the function mt_srand() to seed the random number generator and pass it MT_RAND_PHP as the value of the second parameter.

The function mt_rand() has period 2 19937 −1, which means in the best case you get a random number of 2 19937 −1 before the string starts repeating. You should note that repeating a string is not the same as repeating a specific number. In other words, you could get the same random number twice, but that doesn't mean that the sequence itself started repeating. The following sequence is an example:

187 3276 1267 15 1267 34598 3467 125 17

In the above string, we've got 1267 twice in the result, but that doesn't mean the entire string starts repeating after that. It is not possible to have the same number of such early iterations in a random sequence, but it is possible!

Securely encrypted random integers

If you want cryptographically secure random pseudo numbers, random_int() PHP functions are your best bet. It will generate random numbers between values $minand $maxare given, default is PHP_INT_MIN and PHP_INT_MAX. Unfortunately, this function has only started in support since PHP 7.0. For earlier versions, you can use this polyfill on GitHub .

Random floats

Instead of generating random integers, you probably want to generate floats too. This can be done easily by dividing a random number by the value returned by mt_getrandmax(). The following example will illustrate how to generate a random float number between 0 and 1 or between any other minimum and maximum limits.

<?php

 

// Output: 0.69458310943776

echo mt_rand(0, mt_getrandmax())/mt_getrandmax();

 

function mt_random_float($min, $max) {

    $float_part = mt_rand(0, mt_getrandmax())/mt_getrandmax();

    $integer_part = mt_rand($min, $max - 1);

    return $integer_part + $float_part;

}

 

// Output: 10.199064863938

echo mt_random_float(10, 11);

 

// Output: 35.540808309121

echo mt_random_float(15, 50);

 

?>

 

When generating random floats between certain bounds, we make sure that the random integers are not exceeded $max - 1. This way, we can be sure that adding floats will not take the number above the maximum limit.

The seed for the random number generator

php random number One concept that needs a little explanation are seeds. Simply put, these are just numbers that can be used to initialize functions rand()and mt_rand()before generating any random numbers. The function where seed rand() is called srand($seed) and the function that produces the seed mt_rand() is called mt_srand($seed, $mode).

It is important to remember that giving an initial seed value each time before calling rand() and mt_rand() will not necessarily generate better random numbers. Using the same seed every time will give you the same random number!

 

<?php

 

mt_srand(10);

// Output: 1656398468

echo mt_rand();

 

mt_srand(10);

// Output: 1656398468

echo mt_rand();

 

mt_srand(10);

// Output: 1656398468

echo mt_rand();

 

?>

 

Seed a random number is useful in situations where you want to generate a repeatable but random sequence. The following code generates the same sequence of random numbers when run twice.

 

<?php

 

mt_srand(10);

 

$count = 0;

 

while($count < 10) {

    echo mt_rand(0, 100)." ";

    $count++;

}

 

// Output on First Run:

// 68 58 68 13 3 48 30 37 96 82

 

// Output on Second Run:

// 68 58 68 13 3 48 30 37 96 82

 

Generating repetitive random strings in this way can help debug programs being tested using random data if you track seed, you can copy the same input. to find the wrong error.

Generate random string in PHP

There are many ways to generate random strings of alphanumeric characters and what you use will depend on your needs php random string.

Create scrambled chains

If you want to generate random alphanumeric strings from a fixed character set, you can use the function str_shuffle($string). This function will return you a string of random shuffles. Starting in PHP 7.1, the algorithm for determining the random order of characters in the result string has been changed to Mersenne Twister.

Remember that random strings generated in this way are not cryptographically secure. However, the string will still be unpredictable due to popular usages like filename generation or random URL generation. Here are a few examples:

 

<?php

 

$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';

// Output: 54esmdr0qf

echo substr(str_shuffle($permitted_chars), 0, 10);

 

$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Output: video-g6swmAP8X5VG4jCi.mp4

echo 'video-'.substr(str_shuffle($permitted_chars), 0, 16).'.mp4';

 

?>

 

Your results may differ in both cases. In the first case, we just shuffle the allowed string and then take the first 10 chars of that string. In the second case, we added "video" to the beginning of the generated string and ".mp4" at the end.

This method of generating random strings of alphanumeric characters is very easy but has a few problems. For example, you will never get the same characters in your random string twice. Also, the length of the random result string can only be as long as the input string.

Generate random strings

If the problems I listed above are a spoiler of the problem, you might want to consider some other implementations. The following code will solve both of these problems php generate random string.

 

<?php

 

$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

 

function generate_string($input, $strength = 16) {

    $input_length = strlen($input);

    $random_string = '';

    for($i = 0; $i < $strength; $i++) {

        $random_character = $input[mt_rand(0, $input_length - 1)];

        $random_string .= $random_character;

    }

 

    return $random_string;

}

 

// Output: iNCHNGzByPjhApvn7XBD

echo generate_string($permitted_chars, 20);

 

// Output: 70Fmr9mOlGID7OhtTbyj

echo generate_string($permitted_chars, 20);

 

// Output: Jp8iVNhZXhUdSlPi1sMNF7hOfmEWYl2UIMO9YqA4faJmS52iXdtlA3YyCfSlAbLYzjr0mzCWWQ7M8AgqDn2aumHoamsUtjZNhBfU

echo generate_string($permitted_chars, 100);

 

?>

 

You can modify it to add specific suffixes and prefixes to the newly generated random string. Those using PHP 7 can further improve string generation by using the cryptographic security function random_int() instead mt_rand().

Generate random hexadecimal (hexadecimal) string

If you want to generate random hexadecimal strings in PHP, you can also use function md5($string, $rawDefput) or function sha1($string, $rawDefput). Both will generate the hash of an input string.

You will continue to get unique hashes as long as the input is unique. This can be achieved by using the result of the function as time()input. By default, md5() 32-character hexadecimal string sha1()will be returned and a 40-character hexadecimal string will be returned. They can be cut to a specific length using a function substr().

Here is an example of the results returned by these functions:

 

<?php

 

// Output: 36e5e490f14b031e

echo substr(md5(time()), 0, 16);

 

// Output: aa88ef597c77a5b3

echo substr(sha1(time()), 0, 16);

 

// Output: 447c13ce896b820f353bec47248675b3

echo md5(time());

 

// Output: 6c2cef9fe21832a232da7386e4775654b77c7797

echo sha1(time());

 

?>

 

As you can see, generating random and unique hexadecimal strings up to 40 characters long is very easy in PHP.

Generate cryptographic random strings

The three functions for generating random alphanumeric strings that we have discussed so far do not have encryption security. Fortunately, PHP also has a function random_bytes($length) for generating encrypted, encrypted random bytes. The parameter that $lengthdetermines how long the resulting string will be.

When you have the results as random bytes, you can use the function bin2hex() to convert them to hexadecimal values. This will double the length of the string.

 

<?php

 

// Output: b7b33efa07915b60ad55

echo bin2hex(random_bytes(10));

 

// Output: a2e6cb1f25616324c8a11a2cceb0b47c590949ea

echo bin2hex(random_bytes(20));

 

// Output: 25af3b86e11884ef5e8ef70a0ad06cba81b89ed6af3781a0

echo bin2hex(random_bytes(24));

 

?>

 

Another function that you can use to generate encrypted, random bytes is openssl_random_pseudo_bytes($length, & $crypto_strong). The value of the second parameter can be used to determine whether the resulting string will be generated using a cryptographic security algorithm.

Summary

In this tutorial, we looked at generating random numbers and literal strings in PHP. Generating random numbers can be useful in many situations, like in games where you have to generate enemies or randomly give players some clues about the letters they can form. a complete word.

Just like random numbers, generating random strings of letters and numbers can also be quite useful in many cases. With your help str_shuffle(), you can choose which set of characters appear in your random string. With sha1() and md5() you can easily generate random hexadecimal strings, and with Random_bytes() you can generate cryptographically secure strings. This will allow you to generate random but unpredictable filenames and username.

I hope you enjoyed this tutorial. If you have any questions, feel free to post them in the comments.

Source: code.tutsplus.com