PHPackages                             intelogie/random\_compat - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. intelogie/random\_compat

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

intelogie/random\_compat
========================

PHP 5.x polyfill for random\_bytes() and random\_int() from PHP 7

v2.0.2(10y ago)0148MITPHPPHP &gt;=5.2.0

Since Jul 7Pushed 10y ago1 watchersCompare

[ Source](https://github.com/INTELOGIE/random_compat)[ Packagist](https://packagist.org/packages/intelogie/random_compat)[ RSS](/packages/intelogie-random-compat/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (1)Versions (42)Used By (0)

random\_compat
==============

[](#random_compat)

[![Build Status](https://camo.githubusercontent.com/eaf3dde800c165076a61a794a734e0923590c353e4db9b6aa6f7b18eaca5e9b4/68747470733a2f2f7472617669732d63692e6f72672f70617261676f6e69652f72616e646f6d5f636f6d7061742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/paragonie/random_compat)[![Scrutinizer](https://camo.githubusercontent.com/38350ce871986130f3597da13d6283f5072a2afada220e310e5cf9599807087e/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f70617261676f6e69652f72616e646f6d5f636f6d7061742f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/paragonie/random_compat)

PHP 5.x polyfill for `random_bytes()` and `random_int()` created and maintained by [Paragon Initiative Enterprises](https://paragonie.com).

Although this library *should* function in earlier versions of PHP, we will only consider issues relevant to [supported PHP versions](https://secure.php.net/supported-versions.php). **If you are using an unsupported version of PHP, please upgrade as soon as possible.**

Important
---------

[](#important)

Although this library has been examined by some security experts in the PHP community, there will always be a chance that we overlooked something. Please ask your favorite trusted hackers to hammer it for implementation errors and bugs before even thinking about deploying it in production.

**Do not use the master branch, use a [stable release](https://github.com/paragonie/random_compat/releases/latest).**

For the background of this library, please refer to our blog post on [Generating Random Integers and Strings in PHP](https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php).

### Usability Notice

[](#usability-notice)

If PHP cannot safely generate random data, this library will throw an `Exception`. It will never fall back to insecure random data. If this keeps happening, upgrade to a newer version of PHP immediately.

Installing
----------

[](#installing)

**With [Composer](https://getcomposer.org):**

```
composer require paragonie/random_compat

```

**Signed PHP Archive:**

As of version 1.2.0, we also ship an ECDSA-signed PHP Archive with each stable release on Github.

1. Download [the `.phar`, `.phar.pubkey`, and `.phar.pubkey.asc`](https://github.com/paragonie/random_compat/releases/latest) files.
2. (**Recommended** but not required) Verify the PGP signature of `.phar.pubkey`(contained within the `.asc` file) using the [PGP public key for Paragon Initiative Enterprises](https://paragonie.com/static/gpg-public-key.txt).
3. Extract both `.phar` and `.phar.pubkey` files to the same directory.
4. `require_once "/path/to/random_compat.phar";`
5. When a new version is released, you only need to replace the `.phar` file; the `.pubkey` will not change (unless our signing key is ever compromised).

**Manual Installation:**

1. Download [a stable release](https://github.com/paragonie/random_compat/releases/latest).
2. Extract the files into your project.
3. `require_once "/path/to/random_compat/lib/random.php";`

Usage
-----

[](#usage)

This library exposes the [CSPRNG functions added in PHP 7](https://secure.php.net/manual/en/ref.csprng.php)for use in PHP 5 projects. Their behavior should be identical.

### Generate a string of random bytes

[](#generate-a-string-of-random-bytes)

```
try {
    $string = random_bytes(32);
} catch (TypeError $e) {
    // Well, it's an integer, so this IS unexpected.
    die("An unexpected error has occurred");
} catch (Error $e) {
    // This is also unexpected because 32 is a reasonable integer.
    die("An unexpected error has occurred");
} catch (Exception $e) {
    // If you get this message, the CSPRNG failed hard.
    die("Could not generate a random string. Is our OS secure?");
}

var_dump(bin2hex($string));
// string(64) "5787c41ae124b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2eeac6f"
```

### Generate a random integer between two given integers (inclusive)

[](#generate-a-random-integer-between-two-given-integers-inclusive)

```
try {
    $int = random_int(0, 255);
} catch (TypeError $e) {
    // Well, it's an integer, so this IS unexpected.
    die("An unexpected error has occurred");
} catch (Error $e) {
    // This is also unexpected because 0 and 255 are both reasonable integers.
    die("An unexpected error has occurred");
} catch (Exception $e) {
    // If you get this message, the CSPRNG failed hard.
    die("Could not generate a random int. Is our OS secure?");
}

var_dump($int);
// int(47)
```

### Exception handling

[](#exception-handling)

When handling exceptions and errors you must account for differences between PHP 5 and PHP7.

The differences:

- Catching `Error` works, so long as it is caught before `Exception`.
- Catching `Exception` has different behavior, without previously catching `Error`.
- There is *no* portable way to catch all errors/exceptions.

#### Our recommendation

[](#our-recommendation)

**Always** catch `Error` before `Exception`.

#### Example

[](#example)

```
try {
    return random_int(1, $userInput);
} catch (TypeError $e) {
    // This is okay, so long as `Error` is caught before `Exception`.
    throw new Exception('Please enter a number!');
} catch (Error $e) {
    // This is required, if you do not need to do anything just rethrow.
    throw $e;
} catch (Exception $e) {
    // This is optional and maybe omitted if you do not want to handle errors
    // during generation.
    throw new InternalServerErrorException(
        'Oops, our server is bust and cannot generate any random data.',
        500,
        $e
    );
}
```

### Troubleshooting

[](#troubleshooting)

**Exception: "Could not gather sufficient random data"**

If an Exception is thrown, then your operating system is not secure.

1. If you're on Windows, make sure you enable mcrypt.
2. If you're on any other OS, make sure `/dev/urandom` is readable.
    - FreeBSD jails need to expose `/dev/urandom` from the host OS
    - If you use `open_basedir`, make sure `/dev/urandom` is allowed

This library does not (and will not accept any patches to) fall back to an insecure random number generator.

Contributors
------------

[](#contributors)

This project would not be anywhere near as excellent as it is today if it weren't for the contributions of the following individuals:

- [@AndrewCarterUK (Andrew Carter)](https://github.com/AndrewCarterUK)
- [@asgrim (James Titcumb)](https://github.com/asgrim)
- [@bcremer (Benjamin Cremer)](https://github.com/bcremer)
- [@CodesInChaos (Christian Winnerlein)](https://github.com/CodesInChaos)
- [@chriscct7 (Chris Christoff)](https://github.com/chriscct7)
- [@cs278 (Chris Smith)](https://github.com/cs278)
- [@cweagans (Cameron Eagans)](https://github.com/cweagans)
- [@dd32 (Dion Hulse)](https://github.com/dd32)
- [@geggleto (Glenn Eggleton)](https://github.com/geggleto)
- [@ircmaxell (Anthony Ferrara)](https://github.com/ircmaxell)
- [@jedisct1 (Frank Denis)](https://github.com/jedisct1)
- [@juliangut (Julián Gutiérrez)](https://github.com/juliangut)
- [@kelunik (Niklas Keller)](https://github.com/kelunik)
- [@lt (Leigh)](https://github.com/lt)
- [@MasonM (Mason Malone)](https://github.com/MasonM)
- [@mmeyer2k (Michael M)](https://github.com/mmeyer2k)
- [@narfbg (Andrey Andreev)](https://github.com/narfbg)
- [@nicolas-grekas (Nicolas Grekas)](https://github.com/nicolas-grekas)
- [@oittaa](https://github.com/oittaa)
- [@oucil (Kevin Farley)](https://github.com/oucil)
- [@redragonx (Stephen Chavez)](https://github.com/redragonx)
- [@rchouinard (Ryan Chouinard)](https://github.com/rchouinard)
- [@SammyK (Sammy Kaye Powers)](https://github.com/SammyK)
- [@scottchiefbaker (Scott Baker)](https://github.com/scottchiefbaker)
- [@skyosev (Stoyan Kyosev)](https://github.com/skyosev)
- [@stof (Christophe Coevoet)](https://github.com/stof)
- [@teohhanhui (Teoh Han Hui)](https://github.com/teohhanhui)
- [@tom-- (Tom Worster)](https://github.com/tom--)
- [@tsyr2ko](https://github.com/tsyr2ko)
- [@trowski (Aaron Piotrowski)](https://github.com/trowski)
- [@twistor (Chris Lepannen)](https://github.com/twistor)
- [@voku (Lars Moelleken)](https://github.com/voku)
- [@xabbuh (Christian Flothmann)](https://github.com/xabbuh)

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 84.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

38

Last Release

3741d ago

Major Versions

v0.9.7 → v1.0.02015-09-07

v1.4.0 → v2.0.02016-03-18

v1.4.1 → v2.0.12016-03-18

v1.x-dev → v2.0.22016-04-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/8cd960536c07e255b2e6f7e55c03c6d09274b215ccceaccc38926ffe03e098a7?d=identicon)[bgauthier](/maintainers/bgauthier)

---

Top Contributors

[![paragonie-scott](https://avatars.githubusercontent.com/u/11591518?v=4)](https://github.com/paragonie-scott "paragonie-scott (251 commits)")[![oittaa](https://avatars.githubusercontent.com/u/8972248?v=4)](https://github.com/oittaa "oittaa (13 commits)")[![dd32](https://avatars.githubusercontent.com/u/767313?v=4)](https://github.com/dd32 "dd32 (4 commits)")[![vinkla](https://avatars.githubusercontent.com/u/499192?v=4)](https://github.com/vinkla "vinkla (4 commits)")[![cweagans](https://avatars.githubusercontent.com/u/101590?v=4)](https://github.com/cweagans "cweagans (3 commits)")[![xabbuh](https://avatars.githubusercontent.com/u/1957048?v=4)](https://github.com/xabbuh "xabbuh (2 commits)")[![jedisct1](https://avatars.githubusercontent.com/u/124872?v=4)](https://github.com/jedisct1 "jedisct1 (2 commits)")[![juliangut](https://avatars.githubusercontent.com/u/1104131?v=4)](https://github.com/juliangut "juliangut (2 commits)")[![stof](https://avatars.githubusercontent.com/u/439401?v=4)](https://github.com/stof "stof (2 commits)")[![nicolas-grekas](https://avatars.githubusercontent.com/u/243674?v=4)](https://github.com/nicolas-grekas "nicolas-grekas (2 commits)")[![skyosev](https://avatars.githubusercontent.com/u/209973?v=4)](https://github.com/skyosev "skyosev (1 commits)")[![teohhanhui](https://avatars.githubusercontent.com/u/548843?v=4)](https://github.com/teohhanhui "teohhanhui (1 commits)")[![twistor](https://avatars.githubusercontent.com/u/42400?v=4)](https://github.com/twistor "twistor (1 commits)")[![mmeyer2k](https://avatars.githubusercontent.com/u/1887431?v=4)](https://github.com/mmeyer2k "mmeyer2k (1 commits)")[![asgrim](https://avatars.githubusercontent.com/u/496145?v=4)](https://github.com/asgrim "asgrim (1 commits)")[![bgauthier](https://avatars.githubusercontent.com/u/1789355?v=4)](https://github.com/bgauthier "bgauthier (1 commits)")[![ConnorVG](https://avatars.githubusercontent.com/u/3260091?v=4)](https://github.com/ConnorVG "ConnorVG (1 commits)")[![cs278](https://avatars.githubusercontent.com/u/17377?v=4)](https://github.com/cs278 "cs278 (1 commits)")[![glensc](https://avatars.githubusercontent.com/u/199095?v=4)](https://github.com/glensc "glensc (1 commits)")[![ircmaxell](https://avatars.githubusercontent.com/u/660654?v=4)](https://github.com/ircmaxell "ircmaxell (1 commits)")

---

Tags

randomcsprngpseudorandom

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/intelogie-random-compat/health.svg)

```
[![Health](https://phpackages.com/badges/intelogie-random-compat/health.svg)](https://phpackages.com/packages/intelogie-random-compat)
```

###  Alternatives

[paragonie/random_compat

PHP 5.x polyfill for random\_bytes() and random\_int() from PHP 7

8.2k686.9M426](/packages/paragonie-random-compat)[ircmaxell/random-lib

A Library For Generating Secure Random Numbers

84031.5M126](/packages/ircmaxell-random-lib)[mistic100/randomcolor

Generate attractive random colors

2411.5M6](/packages/mistic100-randomcolor)[delight-im/random

The most convenient way to securely generate anything random in PHP

2145.8k](/packages/delight-im-random)[pragmarx/random

Create random chars, numbers, strings

744.6M5](/packages/pragmarx-random)[paragonie/random-lib

A Library For Generating Secure Random Numbers

743.6M27](/packages/paragonie-random-lib)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
