Generate random string in PHP

In this example, we will generate a random string using PHP. We will use multiple methods to create random strings in PHP.

There are three different functions for generating random numbers in PHP which accept min and max values and generate a random number from that range. PHP doesn't have any in-built functions to generate random strings but we can use those functions to create new string values.

Below are three functions that will help us to generate random integer values and we define logic on that.

$randomValue = rand(1, 10);

$randomValue = mt_rand(1, 10);

$randomValue = random_int(1, 10);

Above all functions will return random numbers between 1 to 10.

In the first example, we will use loop-based logic to generate a random strings. Where we will define a string variable which contains all allowed characters like 0 to 9, a to z, and A to Z and create a random string from that.

<?php
    function getRandomString($n = 10) {
        // Define allowed character
        $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';

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

        return $randomString;
    }

    echo getRandomString();
?>

Here, we have created a function that accepts one integer parameter and also defined the default value for it. Then created a string variable and add an allowed character to it. Lastly added a loop that runs till the user-defined value and picks a random character from our string and adds it to our random string.

It will produce similar output to the below:

Srcajksjw

Here, we can also use encryption or hash functions to create a random string. Function like md5, hash, or sha1 are used to encrypt data using their functionality. Those encrypted values commonly look like random strings.

Let's take an example to create a random string using an encryption function:

<?php
    function getRandomString(){
        $str = rand();
        return hash("sha256", $str);
    }

    $randomString = getRandomString();
    echo $randomString;

    //2bc8cc1c8cc1f8c8d0eb54210fe52c2d5972e24d11c24748b4def1c5b04fcf18
?>

Here, we can also use uniqid() function to generate random string in PHP. The uniqid() function in PHP is an inbuilt function that is used to generate a unique ID based on the current time in microseconds.

The use of uniqid() function is quite easy to compare to another. Below is example to create random string using uniqid() function:

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

    //2bzdeb79e4b64
?>

Conclusion

In this article, we have taken a few examples to generate random strings in PHP using different logic like custom function, with help of random function and uniqid() function. You can use those as per your requirements.