Skip to content

cloud-rat/string-generator

Repository files navigation

String Generator

CI Latest Version PHPStan Level 9 PHP 8.2+ License: MIT

Fast, cryptographically-secure random string generator for PHP 8.2+.

Zero external dependencies. Uses random_bytes() with bit-packing and rejection sampling for efficient, unbiased output.

Installation

composer require taranovegor/string-generator

Quick start

use TaranovEgor\StringGenerator\CharRange;
use TaranovEgor\StringGenerator\StringGenerator;

$generator = new StringGenerator();

// Default — alphabetic (a-zA-Z)
$token = $generator->generate(32);

// Numeric only
$pin = $generator->generate(6, CharRange::Numeric);

// Alphanumeric
$code = $generator->generate(16, CharRange::AlphaNumeric);

// All printable ASCII
$password = $generator->generate(20, CharRange::Any);

All predefined ranges

Case Characters Size
Numeric 0-9 10
Lowercase a-z 26
Uppercase A-Z 26
Alpha a-z A-Z 52
AlphaNumeric a-z A-Z 0-9 62
Special ! @ # $ % ^ & * and other punctuation 32
Any All printable ASCII (33–126) 94

Custom alphabet

Pass a string as the second argument — every byte in it becomes a valid character:

$generator = new StringGenerator();

// Hex string
echo $generator->generate(32, '0123456789abcdef');

// Base58
echo $generator->generate(22, '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');

// Binary-safe — works with any byte values, including null bytes
echo $generator->generate(64, "\x00\x01\x02\x03");

Note: the alphabet must contain at least 2 distinct characters.

Development

composer install

# Run tests
composer test

# Static analysis (PHPStan)
composer analyse

# Run benchmarks
compose bench

License

The scripts and documentation in this project are released under the MIT License

About

Fast, cryptographically-secure random string generator for PHP 8.2+

Topics

Resources

License

Stars

Watchers

Forks

Contributors

Languages