How to Generate a Random String with PHP

In the framework of this snippet, we will explain several ways of generating a unique, random string with the help of PHP arsenal.

Using the Brute Force

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

  • Storing all the possible letters into strings.
  • Generating a random index from 0 to the length of the string -1.
  • Printing the letter on the given index.
  • Implementing the steps n times (n is considered the length of the required string).
  • Here is an example:

    <?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);

    Here is the first output:

    3HDrSOvRIs

    And, the second one:

    lipHh

    Applying Hashing Functions

    In PHP, there are several functions such as md5(), sha1(), and hash() that might be applied for hashing a string based on exact algorithms such as “sha1”, “sha256”, “md5”, and so on.

    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:

    1. Generating a random number with the rand() function.
    2. Hashing it with one of the functions above.

    Here is an example:

    <?php
    
    $str = rand();
    $result = md5($str);
    echo $result;
    
    ?>

    The output will look like this:

    2e437510c181dd2ae100fc1661a445d4

    Applying the Uniqid() Function

    This is an inbuilt function that is applied for generating a unique ID built on the current time in microseconds. It returns a 13-character long unique string, by default.

    The example is demonstrated below:

    <?php
    
    $result = uniqid();
    echo $result;
    
    ?>

    The first output is the following:

    5bdd0b74e9a6c

    Here is the second one:

    5bdd0bbc200c4

    Please, take into consideration that all the methods above are based on rand() and uniqid() functions. However, they are not considered cryptographically secure random generators.

    Using Random_bytes() Function ( The Most Secured)

    If you want to generate cryptographically secure pseudo random bytes that can be converted into a hexadecimal format with the bin2hex() function, then you should use the random_bytes function.

    Here is an example:

    <?php
    
    $n = 20;
    $result = bin2hex(random_bytes($n));
    echo $result;
    
    ?>

    Here is the first output:

    235aed08a01468f90fa726bd56319fb893967da8

    The second one:

    508b84494cdf31bec01566d12a924c75d4baed39

    So, in this snippet, we represented several ways to generate a random string with PHP. Learning them will make your work easier and more productive.