PHPackages                             valorin/random - 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. valorin/random

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

valorin/random
==============

Random is a simple helper package designed to make it easy to generate a range of different cryptographically secure random values.

v1.0.1(1y ago)228188.4k—6%122MITPHPPHP ^7.1 || ^8.0CI passing

Since Dec 30Pushed 9mo ago3 watchersCompare

[ Source](https://github.com/valorin/random)[ Packagist](https://packagist.org/packages/valorin/random)[ Docs](https://github.com/valorin/random)[ GitHub Sponsors](https://github.com/valorin)[ RSS](/packages/valorin-random/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (3)Versions (9)Used By (2)

[![](https://github.com/valorin/random/actions/workflows/php.yml/badge.svg)](https://github.com/valorin/random/actions/workflows/php.yml)[![Total Downloads](https://camo.githubusercontent.com/e7df69b3a43724a91c0dab9b3c8e8d0d23b668a0b918b78d00e01d838a808db9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f76616c6f72696e2f72616e646f6d)](https://packagist.org/packages/valorin/random)[![Latest Stable Version](https://camo.githubusercontent.com/f03176523fb1ad4c4f71198fb1179e78519b04445a0d56d5edff5bd6c1557e4d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f76616c6f72696e2f72616e646f6d)](https://packagist.org/packages/valorin/random)[![License](https://camo.githubusercontent.com/56b0addc19a6af43a01a547c2881bdce208034ec4a7e05a3f3600a81cacfeeab/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f76616c6f72696e2f72616e646f6d)](https://packagist.org/packages/valorin/random)

`Random` by [Valorin](https://stephenreescarter.net/)
=====================================================

[](#random-by-valorin)

Random generates cryptographically secure random values in a range of different formats through a simple helper package for PHP.

Random was created because I was constantly encountering weak and insecure random value generations within apps during my [Laravel and PHP Security Audits](https://valorinsecurity.com/) and I wanted a secure solution to point my clients to without needing them to implement secure algorithms themselves. The idea was then expanded out a bit to support all the common random value types I've encountered.

Random is completely framework agnostic, the only production dependency is the excellent [php-random-polyfill](https://github.com/arokettu/php-random-polyfill), which does nothing on PHP 8.2+ where the functions are included in core. It supports Laravel's Collections, but doesn't pull in any Laravel code.

You can find more about Random in the [Securing Laravel In Depth article](https://securinglaravel.com/p/in-depth-introducing-random).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require valorin/random
```

There is no need to install any service providers, Random should just work out of the box.

Random is supported on PHP 7.1 and later.

Usage
-----

[](#usage)

Random is designed to be as simple as possible to use. It's a static class, so you can just call the methods directly.

Import the class into your namespace:

```
use Valorin\Random\Random;
```

### Random Integers

[](#random-integers)

Generate a random integer between `$min`, and `$max` (inclusive):

```
$number = Random::number(int $min, int $max): int;
```

Note, this is only really useful if you're using a specific [Randomizer Engine](https://www.php.net/manual/en/book.random.php) (such as when using seeds). For most use cases, I'd suggest sticking with `random_int()` for simplicity.

### Random One-Time Password (Numeric fixed-length OTPs)

[](#random-one-time-password-numeric-fixed-length-otps)

Generate a random numeric one-time password (OTP) of `$length` digits:

```
$otp = Random::otp(int $length): string;
```

This is useful for generating OTPs for SMS or email verification codes. These are commonly done using `rand(100000, 999999)`, which is both insecure and also loses 10% of the possible codes in the `0-99999` range. This provides a secure alternative which includes the full `000000-999999` range (with variable length).

### Random String

[](#random-string)

Generate a random string of `$length` characters which includes characters from the enabled character types. By default, it will randomly select characters and not guarantee any specific character types are present. If you require one of each character to be included, you can set `$requireAll = true`.

```
// Primary method
$string = Random::string(
    int $length = 32,
    bool $lower = true,
    bool $upper = true,
    bool $numbers = true,
    bool $symbols = true,
    bool $requireAll = false
): string;
```

The following are wrappers for common use cases:

```
// Random letters only
$letters = Random::letters(int $length = 32): string;

// Random alphanumeric (letters and numbers) token string
$token = Random::token(int $length = 32): string;

// Random letters, numbers, and symbols (i.e. a random password).
$password = Random::password(int $length = 16, bool $requireAll = false): string;

// Random alphanumeric token string with chunks separated by dashes, making it easy to read and type.
$password = Random::dashed(int $length = 25, string $delimiter = '-', int $chunkLength = 5, bool $mixedCase = true): string;
```

To limit the characters available in any of the types (i.e. lower, upper, numbers, or symbols), you can create a custom Generator instance with your customer character set:

```
// Override just symbols
$generator = Random::useSymbols(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')'])->string();

// Override everything
$generator = Random::useLower(range('a', 'f'))
    ->useUpper(range('G', 'L'))
    ->useNumbers(range(2, 6))
    ->useSymbols(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')']);

$string = $generator->string(
    $length = 32,
    $lower = true,
    $upper = true,
    $numbers = true,
    $symbols = true,
    $requireAll = true
);
```

Note, you can chain the `use*()` methods in any order, and they will persist within that Generator only.

### Shuffle Array, String, or Collection

[](#shuffle-array-string-or-collection)

Securely shuffle an array, string, or Laravel Collection, optionally preserving the keys.

```
$shuffled = Random::shuffle(
    array|string|\Illuminate\Support\Collection $values,
    bool $preserveKeys = false
): array|string|\Illuminate\Support\Collection;
```

### Pick `$count` Items or Characters

[](#pick-count-items-or-characters)

Securely pick `$count` items (or characters) from an array or Laravel Collection.

```
$picks = Random::pick(
    array|\Illuminate\Support\Collection $values,
    int $count
): array|\Illuminate\Support\Collection;
```

Will return the picks in the same type as `$values`, so either as an array or a Collection.

To pick a single item, use the `single()` method (or `pickOne()` alias) to select a single item and return just that item. This also supports strings, and will return a single character from the string.

```
$pick = Random::single(
    array|string|\Illuminate\Support\Collection $values
): array|string|\Illuminate\Support\Collection;
```

### Using a specific `\Random\Engine`

[](#using-a-specific-randomengine)

By default `Random` will use the secure default `\Random\Engine` defined by PHP. To use a different Engine, pass it to the `use()` method and call the above methods on the returned `Generator` class.

```
$generator = Random::use(\Random\Engine $engine): \Valorin\Random\Generator;
```

The primary use case for `use()` is when you need to specify a specific random seed, in order to control the output. Only the returned `\Valorin\Random\Generator` object will use the provided Engine (and seed), allowing you to create and use the Generator independently of other uses of `Random` within your app.

```
$generator = Random::use(new \Random\Engine\Mt19937(3791));

$number = $generator->number(1, 1000);
$password = $generator->password();
```

You can use `use()` alongside the character set helpers (`useLower()`, `useUpper()`, `useNumbers()`, `useSymbols()`), although you will need to call `use()` first to define the Engine before customising the character set on the `Generator` object.

Support My Work! ❤️
-------------------

[](#support-my-work-️)

You can support my work over on [GitHub Sponsors](https://github.com/sponsors/valorin)or by becoming a paid subscriber to [Securing Laravel](https://securinglaravel.com/), the essential security resource for Laravel and PHP developers!

Contributing
------------

[](#contributing)

Contributions are very welcome! There isn't a formal guide, but throw in an Issue or PR, and we'll go from there.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please report any security vulnerabilities via the [GitHub project](https://github.com/valorin/random)or by contacting [Stephen Rees-Carter directly](https://stephenreescarter.net/.well-known/security.txt).

License
-------

[](#license)

Random is open-source software licensed under the [MIT license](LICENSE.md).

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance52

Moderate activity, may be stable

Popularity52

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 79.1% 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 ~63 days

Recently: every ~107 days

Total

8

Last Release

427d ago

Major Versions

v0.6 → v1.02025-03-12

PHP version history (2 changes)v0.1PHP ^7.1 | ^8.0

v0.3PHP ^7.1 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/6c2eb86dddee75463a43c6457f38413b61cc0009232881df800a3842e2d89f7b?d=identicon)[valorin](/maintainers/valorin)

---

Top Contributors

[![valorin](https://avatars.githubusercontent.com/u/897369?v=4)](https://github.com/valorin "valorin (68 commits)")[![faissaloux](https://avatars.githubusercontent.com/u/60013703?v=4)](https://github.com/faissaloux "faissaloux (6 commits)")[![shatterproof](https://avatars.githubusercontent.com/u/4100078?v=4)](https://github.com/shatterproof "shatterproof (5 commits)")[![szepeviktor](https://avatars.githubusercontent.com/u/952007?v=4)](https://github.com/szepeviktor "szepeviktor (3 commits)")[![localheinz](https://avatars.githubusercontent.com/u/605483?v=4)](https://github.com/localheinz "localheinz (2 commits)")[![princejohnsantillan](https://avatars.githubusercontent.com/u/60916966?v=4)](https://github.com/princejohnsantillan "princejohnsantillan (2 commits)")

---

Tags

php

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[imanghafoori/laravel-anypass

A minimal yet powerful package to help you in development.

21421.6k](/packages/imanghafoori-laravel-anypass)

PHPackages © 2026

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