How to generate random string in PHP?

In this article, we will cover how to generate random string in PHP and it’s application in various fields.

Create random strings for a fixed length

In this section, we will discuss the generation of the random string for a fixed length. There are two ways to achieve that:

  • Using a predefined function
  • Using a user-defined function

let us take an example of a pre-defined function for generating strings,

$str = 'abcdefgh';//range for string generation
$shufflestr = str_shuffle($str);//used to shuffle the range of strings
echo $shufflestr;




  • The limitation of the above-predefined function is that you cannot specify more character sets than the given length.

So, to overcome this, we need a user-defined function. Let us take an example of a user-definedĀ  function:


function RandomString($num) 
  // Variable that store final string 
  $final_string = ""; 
  //Range of values used for generating string
  $range = "[email protected]#$^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 
  // Find the length of created string 
  $length = strlen($range); 
  // Loop to create random string 
  for ($i = 0; $i < $num; $i++) 
    // Generate a random index to pick 
    // characters 
    $index = rand(0, $length - 1); 
    // Concatenating the character 
    // in resultant string 
  // Return the random generated string 
  return $final_string; 

//Creating call to test above function 
$num = 5; 
echo "Random String of length " . $num
. " = " . RandomString($num); 


Random String of length 5 = [email protected]


For variable length string, just take input through an HTML page and pass it to theĀ PHP page.

Real world application of Random String

There are several examples, but I am taking one of the examples of password generation for a login page. Let us assume some rules for that-

  • The string should be of 8 characters long.
  • The first letter should be capital.
  • It must contain one special character([email protected]#$^*~).
  • It must contain at least one number.
  • It must contain at least one letter.

Let us make simple coding for that,

$arr="[email protected]#$^&*~";//set of special character allowed
//string must be atleast 8 character long
for ($i = 1; $i <=8; $i++){
    $random_string = $random_string.chr(rand(65,90));//first letter should be capital
        $random_string = $random_string.$arr[rand(0,strlen($arr)-1)];//string contains at least one special character 
      $random_string = $random_string.chr(rand(97,122));//rest are maybe alphabet
      $random_string = $random_string.chr(rand(48,57));//rest are maybe digit
echo $random_string;



In this way, we can generate strings in a random manner in PHP. If you have any doubt, leave us a comment.

See also,

Leave a Reply

Your email address will not be published. Required fields are marked *