Monday, January 7, 2013

Creating a Random String in PHP

Introduction
You can create a random string in PHP using the PHP built-in rand function. It might be for a complex password, a verification code, or something for developing. Basically it is used when you want to save time, in other words saving your manual process time, nothing more. In the following I present a simple way to create a random string in PHP step-by-step.

Step 1


Create a PHP rand_string function
First, you can create a PHP function with one (1) parameter specifying the length.

function rand_string ($length){...body}

It is used to generate a random string.

Step 2

Take a Variable
After that you can use a string variable with the name of char.

$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
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:

$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str= $chars[ rand( 0, $size - 1 ) ];
echo $str;
}

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

Example

php
function rand_string( $length ) {
       $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";  
       $size = strlen( $chars );
       echo "Random string =";
       for( $i = 0; $i < $length; $i++ ) {
              $str= $chars[ rand( 0, $size - 1 ) ];
              echo $str;
       }
}
 rand_string( 5 );
?>

No comments:

Post a Comment