W3docs

How to Generate a Random String with PHP

This tutorial includes several methods of generating a unique, random, alpha-numeric string with PHP. Follow the examples below, it will be easily done.

In this tutorial, we will explain several ways of generating a unique, random string with PHP.

Using the Brute Force

The first way is using brute force. It is the simplest method and can be achieved by following the steps below:

  1. Storing all the possible characters into a string.
  2. Generating a random index from <kbd class="highlighted">0</kbd> to the length of the string <kbd class="highlighted">-1</kbd>.
  3. Selecting the character at the given index.
  4. Repeating the steps <kbd class="highlighted">n</kbd> times (<kbd class="highlighted">n</kbd> is the desired length of the string).

Here is an example:

php getname function

<?php

$n = 10;
function getRandomString($n)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}

echo getRandomString($n);

Note: The rand() function is deprecated in PHP 8.1+. For non-cryptographic use, consider random_int() instead.

Here is the first output:

php getname output

3HDrSOvRIs

And, the second one:

php getname output

lipHh

Applying Hashing Functions

PHP provides several functions, such as <kbd class="highlighted">md5()</kbd>, <kbd class="highlighted">sha1()</kbd>, and <kbd class="highlighted">hash()</kbd>, which can generate fixed-length strings from input data.

All of these functions are capable of taking a string as an argument and output an alphanumeric hashed string.

To use them for this purpose, follow these steps:

  1. Generating a random number with the <kbd class="highlighted">rand()</kbd> function.
  2. Hashing it with one of the functions above.

Here is an example:

php rand() function

<?php

$str = rand();
$result = md5($str);
echo $result;

?>

Note: Hashing a random number is not a standard method for generating secure random strings. Use random_bytes() for security-sensitive applications.

The output will look like this:

php rand() function output

2e437510c181dd2ae100fc1661a445d4

Applying the Uniqid() Function

This built-in function generates a unique ID based on the current time in microseconds. By default, it returns a 13-character string.

The example is demonstrated below:

php uniqid() function

<?php

$result = uniqid();
echo $result;

?>

The first output is the following:

php uniqid() function output

5bdd0b74e9a6c

Here is the second one:

php uniqid() function output

5bdd0bbc200c4

Please note that all the methods above rely on <kbd class="highlighted">rand()</kbd> and <kbd class="highlighted">uniqid()</kbd>, which are not cryptographically secure random generators.

Using Random_bytes() Function (The Most Secure)

To generate cryptographically secure pseudo-random bytes and convert them to a hexadecimal string, use the <kbd class="highlighted">random_bytes()</kbd> function combined with <kbd class="highlighted">bin2hex()</kbd>.

Here is an example:

php random_bytes function

<?php

$n = 20;
$result = bin2hex(random_bytes($n));
echo $result;

?>

Note: The $n parameter specifies the number of bytes, not characters. Since bin2hex() doubles the length, the output will be 2 * $n characters long.

Here is the first output:

php random_bytes output

235aed08a01468f90fa726bd56319fb893967da8

The second one:

php random_bytes output

508b84494cdf31bec01566d12a924c75d4baed39

This tutorial covered several methods for generating random strings in PHP. Choose the approach that best fits your security and performance requirements.