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 random strings. Where we will define a string variable that contains all allowed characters like 0 to 9, a to z, and A to Z, and create a random string from that.

    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 create a string variable and add an allowed character to it. Lastly added a loop that runs till the user-defined value picks a random character from our string and adds it to our random string.

It will produce a similar output to the below:


Here, we can also use encryption or hash functions to create a random string. Functions 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:

    function getRandomString(){
        $str = rand();
        return hash("sha256", $str);

    $randomString = getRandomString();
    echo $randomString;


Here, we can also use uniqid() function to generate a 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 an example of creating random string using uniqid() function:

    $result = uniqid();
    echo $result;



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