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.
composer require taranovegor/string-generatoruse TaranovEgor\StringGenerator\Alphabet;
use TaranovEgor\StringGenerator\StringGenerator;
$generator = new StringGenerator();
// Default — alphanumeric (a-zA-Z0-9)
$token = $generator->generate(32);
// Digits only
$pin = $generator->generate(6, Alphabet::Digits);
// Letters only
$code = $generator->generate(16, Alphabet::Alpha);
// All printable ASCII
$password = $generator->generate(20, Alphabet::Printable);| Case | Characters | Size |
|---|---|---|
Digits |
0-9 |
10 |
AlphaLower |
a-z |
26 |
AlphaUpper |
A-Z |
26 |
Alpha |
a-z A-Z |
52 |
Alphanumeric |
a-z A-Z 0-9 |
62 |
Punctuation |
32 punctuation characters (`!"#$%&'()*+,-./:;<=>?@[]^_{ | }~`) |
Printable |
All printable ASCII (33–126) | 94 |
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 bytes.
composer install
# Run tests
composer test
# Static analysis (PHPStan level 9)
composer analyseThe scripts and documentation in this project are released under the MIT License