Random String in PHP

PHP rand function

 
You can create a random string in PHP using the rand function. A random string may be a complex password, a verification code, or anything else. Automating random string can save time and reduce the manual process in applications. Rather than creating your own logic of random strings, we can use the rand funtion.
 
In this step by step tutorial, I'll create and use a random string in PHP.
 

Step 1. Create a PHP rand_string function

 
First, create a PHP function with one (1) parameter specifying the length of the random string to be created.
  1. function rand_string ($length){...body}  
It is used to generate a random string.
 

Step 2. Declare a Variable

 
Let's declare a string variable with the name of char.
  1. $char="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";  
It contains a collection of various types of strings. When a function generates a random string, all of the characters are fetched from it.
 

Step 3. Random generator

 
We will refer to parts of this String using a random generator. Once we generate a random integer index, we add the corresponding character – the character at that index – to a finished String. This can be completed using a loop:
  1. $size = strlen$chars );  
  2. for$i = 0; $i < $length$i++ ) {  
  3. $str$chars[ rand( 0, $size - 1 ) ];  
  4. echo $str;  
  5. }

 

Step 4. Call rand_string() function
 
rand_string( 5 );
 

PHP rand Example

 
Here is the comple code example.
 
  1. <?php  
  2. function rand_string( $length ) {  
  3. $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";  
  4. $size = strlen$chars );  
  5. echo "Random string =";  
  6. for$i = 0; $i < $length$i++ ) {  
  7. $str$chars[ rand( 0, $size - 1 ) ];  
  8. echo $str;  
  9. }  
  10. }  
  11. rand_string( 5 );  
  12. ?>  
Note: the above example will not work when the length is greater then $char string length.
 
This is what the output looks like:

random-string-in-php.jpg

 

Summary

 
PHP rand function is used to generate random strings in PHP. In this article, we saw how to use the rand funtion in PHP to generate random strings.  
 


Similar Articles