Generate Random string using 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 value 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 which 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 number between 1 to 10.

In first example, we will use loop based logic to generate random string. Where we will define string variable which contains all allowed character like 0 to 9, a to z and A to Z and create 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 function which accept one integer parameter and also defined default value to it. Then created string variable and add allowed character in it. Lastly added loop which runs till user defined value and pick random character from our string and add it to our random string.

It will produce similar output to below:


Here, we can also use encryption or hash functions to create random string. The function like md5, hash or sha1 used to encrypt data using their functionality. Those encrypted value commonly look like random string.

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

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

    $randomString = getRandomString();
    echo $randomString;


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

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

    $result = uniqid();  
    echo $result;



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

Share your thoughts

Ask anything about this examples