1.2.1356. Use random_int()

rand() and mt_rand() should be replaced with random_int().

At worse, rand() should be replaced with mt_rand(), which is a drop-in replacement and srand() by mt_srand().

random_int() replaces rand(), and has no seeding function like srand().

Other sources of entropy that should be replaced by random_int() : microtime(), uniqid(), time(). Those a often combined with hashing functions and mixed with other sources of entropy, such as a salt. Since PHP 7, random_int() along with random_bytes(), provides cryptographically secure pseudo-random bytes, which are good to be used when security is involved. openssl_random_pseudo_bytes() may be used when the OpenSSL extension is available.

<?php

// Avoid using this
$random = rand(0, 10);

// Drop-in replacement
$random = mt_rand(0, 10);

// Even better but different :
// valid with PHP 7.0+
try {
    $random = random_int(0, 10);
} catch (\Exception $e) {
    // process case of not enoug random values
}

// This is also a source of entropy, based on srand()
// random_int() is a drop-in replacement here
$a = sha256(uniqid());

?>

See also CSPRNG and OpenSSL.

1.2.1356.1. Suggestions

  • Use random_bytes() and randon_int(). At least, use them as a base for random data, and then add extra prefix and suffix, and a hash call on top.

1.2.1356.2. Specs

Short name

Php/BetterRand

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior, CompatibilityPHP71, Security

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Instant (5 mins)

Precision

Very high

Features

random

Examples

Thelia, FuelCMS

Available in

Entreprise Edition, Community Edition, Exakat Cloud