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,
<?php $str = 'abcdefgh';//range for string generation $shufflestr = str_shuffle($str);//used to shuffle the range of strings echo $shufflestr; ?>
Output:
bdaeghfc
Note:-
- 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:
<?php 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 $final_string.=$range[$index]; } // Return the random generated string return $final_string; } //Creating call to test above function $num = 5; echo "Random String of length " . $num . " = " . RandomString($num); ?>
Output:-
Random String of length 5 = [email protected]
Note:-
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,
<?php $random_string=""; $arr="[email protected]#$^&*~";//set of special character allowed $temp=rand(2,8); //string must be atleast 8 character long for ($i = 1; $i <=8; $i++){ if($i==1) $random_string = $random_string.chr(rand(65,90));//first letter should be capital else{ if($i==$temp) $random_string = $random_string.$arr[rand(0,strlen($arr)-1)];//string contains at least one special character else{ $temp2=rand(0,1); if($temp2==0) $random_string = $random_string.chr(rand(97,122));//rest are maybe alphabet else $random_string = $random_string.chr(rand(48,57));//rest are maybe digit } } } echo $random_string; ?>
Output:-
P$cdra6z
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