How do you generate a random number over a 32-bit limit in PHP?

In other languages, I would generate it in parts and save it in a string, but with PHP you can’t choose the data type so that it doesn’t work, set it automatically as an integer, then you can only store the integer size to the maximum.

Is there any solution for this?

+3
source share
6 answers

Yes, you can get some random data (e.g. from /dev/urandomor openssl_random_pseudo_bytes).

Then convert the data to its decimal representation using, for example, bcmath or gmp. See this answer for how to do this.

+3
source

mt_rand(0, 10000) . , :

mt_rand(0, 10000) . mt_rand(0, 10000) . mt_rand(0, 100) - .

, .

+1

. , 0 2 ^ 32-1 ( 8- ). mt_rand() 0 2 ^ 31-1.

:

return hexdec(mt_rand(0,4294967295));

:

return sprintf("%04X%04X", (mt_rand(0,65535)), (mt_rand(0,65535)));

, , . , 0 2 ^ 16-1 (65,535) ( 0000 FFFF), , sprintf .

0 2 ^ 32-1 (hex 00000000 FFFFFFFF) . 48- ( 000000000000 FFFFFFFFFFFF), :

return sprintf("%04X%04X%04X", (mt_rand(0,65535)), (mt_rand(0,65535)), (mt_rand(0,65535)));

!

+1
$i = (int) $i;

.

0

, :

function getBigRandom($length, $space = '0123456789', $trim = true) {
    $str = '';
    $spaceLen = strlen($space);
    for ($i = 0; $i < $length; $i++) {
        $str .= $space[mt_rand(0, $spaceLen - 1)];
    }
    if ($trim) {
        $str = ltrim($str, '0');
    }
    return $str;
}

:

$random = getBigRandom(15); // Generate up to a 15 digit random number

, ... . ( ..), :

$random = getBigRandom(
    128,
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 
    false
);
0
source

Source: https://habr.com/ru/post/1781929/


All Articles