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

Example:

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

The above example will output something similar to:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

More info: http://php.net/manual/en/function.random-bytes.php

PHP 5 (outdated)

I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.

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.


Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure(max)
{
    $range = min;
    if ($range < 1) return $min; // not so random...
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        rnd & $filter; // discard irrelevant bits
    } while (range);
    return rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet); // edited

    for (i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
    }

    return $token;
}

crypto_rand_secure(max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between max.

getToken($length) creates an alphabet to use within the token and then creates a string of length $length.

Source: https://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322

Answer from Scott on Stack Overflow
Top answer
1 of 16
689

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

Example:

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

The above example will output something similar to:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

More info: http://php.net/manual/en/function.random-bytes.php

PHP 5 (outdated)

I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.

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.


Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure(max)
{
    $range = min;
    if ($range < 1) return $min; // not so random...
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        rnd & $filter; // discard irrelevant bits
    } while (range);
    return rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet); // edited

    for (i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
    }

    return $token;
}

crypto_rand_secure(max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between max.

getToken($length) creates an alphabet to use within the token and then creates a string of length $length.

Source: https://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322

2 of 16
346

Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

If you do not need it to be absolutely unique over time:

md5(uniqid(rand(), true))

Otherwise (given you have already determined a unique login for your user):

md5(uniqid($your_user_login, true))
🌐
Envato Tuts+
code.tutsplus.com › generate-random-alphanumeric-strings-in-php--cms-32132t
Generate Random Alphanumeric Strings in PHP | Envato Tuts+
October 29, 2021 - Whether you need to create an email form, add a shopping cart to your eCommerce store, or create a contact form with validation, there's a PHP script that's...
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-generate-a-random-unique-alphanumeric-string-in-php
How to generate a random, unique, alphanumeric string in PHP - GeeksforGeeks
July 4, 2024 - Using `random_int()` in a custom function generates a secure random alphanumeric string by selecting characters from a predefined set. It iterates to build a string of specified length, ensuring cryptographic security.
🌐
Uptimia
uptimia.com › home › questions › how to generate a random alphanumeric string in php?
How To Generate A Random Alphanumeric String In PHP?
November 1, 2024 - This function allows you to define your own set of characters and generate a random string of a specified length using those characters. For PHP versions before 7, the openssl_random_pseudo_bytes() function is an alternative for generating secure ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-generate-a-random-unique-alphanumeric-string-in-php
How to Generate a Random, Unique, Alphanumeric String in PHP
July 28, 2023 - In conclusion, there are several approaches to generate a random, unique alphanumeric string in PHP. The first method demonstrated involved using a combination of character selection and random shuffling, accomplished through the str_shuffle() function.
🌐
Tutorialio
tutorialio.com › generate-a-random-alphanumeric-string-in-php
How Can I Generate a Random Alphanumeric String in PHP?
December 11, 2020 - Here is the second iteration of our function: ... function random_alphanumeric_string($length) { $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle(str_repeat($chars, ceil($length/strlen($chars)) )), 0, $length); } // Output — Z4VIz4gvnb0...
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-generate-random-alphanumeric-string-in-phpexample.html
How to Generate Random Alphanumeric String in PHP? - ItSolutionstuff.com
May 14, 2024 - when you need you generate random alphanumeric string for your unique field then you can easily create using substr(), md5(), rand(), uniqid(), mt_rand(), time() and str_shuffle() php function you can create several way unique code using following ...
🌐
GitHub
gist.github.com › karlgroves › 5227409
PHP Function to create random alphanumeric strings · GitHub
it works for me if u having error on randstr. then change to this function RandomString($length = 32) { $randstr = ' '; then it will work .
Find elsewhere
🌐
The Code Developer
thecodedeveloper.com › home › php › generate random alphanumeric string with php
Generate Random Alphanumeric String with PHP - PHP Tutorial
September 30, 2018 - function random_code($limit) { return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit); } echo random_code(8); //Here's the output samples mocpkwbn 460djcsn j1m10z0t 4kj9cy68 · The base_convert() function is used to convert a number from one base to another. <?php $hexa = 'D174'; echo base_convert($hexa, 18, 8); ?> ... The PHP sha1() function is used to calculate the sha1 hash of a string. ... The PHP uniqid function Generate a unique ID.
🌐
Websistent
websistent.com › php-random-string-generation
PHP random string generation - Jesin's Blog
June 29, 2013 - Generate a random alphanumeric string containing both uppercase and lowercase characters in PHP. The rand() function in PHP generates a random number we’ll be using this function to generate a random alphanumeric string.
🌐
I-fubar
i-fubar.com › random-string-generator.php
Random Alphanumeric String Generator Script in PHP - fubar
We "seed" the random number function ... assign_rand_value($num) accepts that range of numbers. We then use assign_rand_value($num) to change the random number into its corresponding alphanumeric number....
🌐
Envato Tuts+
code.tutsplus.com › tutorials › generate-random-alphanumeric-strings-in-php--cms-32132
Generate Random Alphanumeric Strings in PHP - Code
November 24, 2020 - Whether you need to create an email form, add a shopping cart to your eCommerce store, or create a contact form with validation, there's a PHP script that's...
🌐
GitHub
gist.github.com › irazasyed › 5382685
PHP: Generate random string · GitHub
PHP: Generate random string · Raw · random_strgenerator.php · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
GitHub
gist.github.com › ursuleacv › 80d35b6b6d13fc8760ca
PHP: How to generate a random, unique, alphanumeric string · GitHub
PHP: How to generate a random, unique, alphanumeric string · Raw · gistfile1.txt · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
WP-Mix
wp-mix.com › php-simple-random-string-generator
PHP Simple Random String Generator | WP-Mix
February 1, 2025 - As written, this simple function will output a case-insensitive alphanumeric string. For example, when called as a variable named $random_string: ... That will return some random string that is 10 characters in length, like hsa8h3JsW1. You can change the $length argument to whatever is required. And also can customize the characters that may be used in generating the string.
🌐
W3Docs
w3docs.com › php
How to Generate a Random String with PHP
All of these functions are capable of taking a string as an argument and output an Alpha-Numeric hashed string. After understanding how to utilize the functions, the next steps become simpler: Generating a random number with the rand() function.
🌐
Tuts Make
tutsmake.com › home › generate 6,8,10 digit random, unique, alphanumeric strings and number in php
Generate 6,8,10 digit random, unique, alphanumeric strings and Number in PHP - Tuts Make
June 16, 2024 - In this tutorial, we will show you how you can easily generate 6,8,10,12 digit random, unique, alphanumeric string and number in PHP.
🌐
SitePoint
sitepoint.com › php
How can I generate unique alphanumeric? - PHP - SitePoint Forums | Web Development & Design Community
January 3, 2015 - After building the letter section of the string, generate a random number of appropriate range using rand() If the rand returns a low number with fewer digits than needed (like the last example) append 0’s to the start of it using the ...
🌐
Hellonitish
hellonitish.com › blog › generate-a-random-alphanumeric-string-in-php
Hello Nitish • How Can I Generate a Random Alphanumeric String in PHP?
November 4, 2025 - Here is the second iteration of our function: ... function random_alphanumeric_string($length) { $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle(str_repeat($chars, ceil($length/strlen($chars)) )), 0, $length); } // Output — Z4VIz4gvnb0...