How to generate a random, unique, alphanumeric string in PHP?

Show a number to two decimal places in PHP
convert Numbers to Roman Numbers with PHP

In this solution, you will learn how to generate a random, unique, alphanumeric string in PHP.

solution 1.

PHP 7 standard library provides the random_bytes() function that generates cryptographically secure pseudo-random bytes.

$bytes = random_bytes(20);
var_dump(bin2hex($bytes));

The above example will output something similar to:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

More info here

solution 2.

A quick, short, and to-the-point answer is:

bin2hex(openssl_random_pseudo_bytes($bytes))

Which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately, this only has an alphabet of [a-f][0-9], but it works.

Show a number to two decimal places in PHP
convert Numbers to Roman Numbers with PHP
en English
X
Scroll to Top