PHP RFC: Move RNG functions ext/random


This is due to the historical background, starting with lcg.c / php_lcg.h, the first implementation of the linear congruential generator (LCG), followed by rand.c / php_rand.c, which calls the libc random number implementation, and the Mersenne Twister implementation. mt_rand.c / php_mt_rand.h, an implementation of the Mersenne Twister, and random.c / php_random.h, a CSPRNG implementation, respectively, in the ext/standard extension.

The rand.c / php_rand.h to call the libc implementation is no longer relevant due to its alias to the Mersenne Twister in PHP 7.1, and is left for compatibility only.

RNGs are a frequently used feature in various implementations, and it is suggested that RNG-related functionality be carved out of the ext/standard extension and kindly made into an ext/random extension to reduce complexity and allow for future extensibility.


Create a new ext/random extension and move all the following functions of the ext/standard extension.

Userland Functions:

  • lcg_value()
  • srand()
  • rand()
  • mt_srand()
  • mt_rand()
  • random_int()
  • random_bytes()

Internal APIs:

  • php_random_int_throw()
  • php_random_int_silent()
  • php_combined_lcg()
  • php_srand()
  • php_rand()
  • php_mt_srand()
  • php_mt_rand()
  • php_mt_rand_range()
  • php_mt_rand_common()
  • php_random_bytes()
  • php_random_int()

These features are provided in a single random.c / php_random.h, and ext/random is always bundled with all builds of PHP, as is ext/standard.

Will cause a BC Break for extensions and php-src downstream projects, Means that the following workaround needs to be done to support PHP 8.2 and later.

#if PHP_VERSION_ID >= 80200
#include "ext/random/php_random.h"
#include "ext/standard/php_lcg.h"
#include "ext/standard/php_rand.h"
#include "ext/standard/php_mt_rand.h"
#include "ext/standard/php_random.h"

In general, BC Breaks should be avoided and, as we have done in the past, BC Breaks should not occur unnecessarily.

However, there is now a need to sort these out in order to deal with other problems with PHP random numbers. I think this could be a good reason to allow this BC Break.

See the relevant PHP RFC: Random Extension 3.0 and Internals ML (or the relevant thread in externals) for details.

Backward Incompatible Changes

There are no disruptive changes to userland. However, there will be a BC Break in the downstream project.

Proposed PHP Version(s)

PHP 8.2

RFC Impact



To Existing Extensions

Will need to change the including header file.

To Opcache


New Constants


php.ini Defaults


Open Issues


Patches and Tests



rfc/random_ext.txt · Last modified: 2021/09/06 20:24 by zeriyoshi