pTutorial

New way to learn PHP Example

PHP random string generator with numeric

Random string

In this section we will learn how to create alpha numeric random string that is basically used in password. We can easily generates this string with the help of rand() function.

Random string example

<html>
<body>
<form name= "info" id= "info" method= "post" action= "" >
<strong>Enter length of string</strong>
<input name= "name" type= "text"><br/>
<input type= "submit" name= "Submit" value= "Submit" />
</form>


<?php
$count=0;
$alpha_numeric="";
if(isset($_POST['Submit']))
{
$count=trim($_POST["name"]);
}

$alpha_c = array 
("A", "B", "C", "D", 
"E","F","G","H","I",
"J","K","L","M","N",
"O","P","Q","R","S",
"T","U","V","W","X",
"Y","Z");

$alpha_s = array 
("a", "b", "c", "d",
 "e","f","g","h","i",
 "j","k","l","m","n",
 "o","p","q","r","s",
 "t","u","v","w","x",
 "y","z");

for($i=1; $i <= $count; $i++)
{ 
$b=rand(1,3);
$a=rand(0,25);
if($b == 1)
{
$alpha_numeric .=$alpha_c[$a]; 
}
elseif($b==2)
{
$alpha_numeric .=$alpha_s[$a]; 
} 
else
{
$alpha_numeric .=rand(0,9);
} 
} 

echo $alpha_numeric;
?>
</body>
</html>

Output

Enter length of string

Explanation

In the above example, first create the HTML form that takes the the length of the string through the user.

And after that create two array, one form capital character and one for small character and execute a for loop until we reach the required digit.

Create three random number with the help of rand() function pass it to the if condition, array variable and number(0-9).

Download source code


QUOTES OF THE DAY

Crafty men condemn studies, simple men admire them, and wise use them.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER