Its quiet common in programming, especially web programming to generate random strings as passwords, keys etc. This is a simple function that you can use to generate random string with length of your choice. You can also specify if the string must contain only numbers or alphabets or both.
Input
$type : 3 types, NU (numeric), AL (alphabetic), AN (alphanumeric)
$Len : the length of the returned string.
Generating alphabetic and numeric strings are straightforward. For numeric type, Loop $Len times and use rand() function to generate a number between 0 and 9. For alphabetic type, Loop $Len times and use rand() function to generate a number between 65 and 90. 65 to 90 are character decimal code for characters ‘A’ to ‘Z’. See the ACSII chart for more information.
The alphanumeric values are generated by first generating a random value between 0 and 1 .If this value is above 0 we generate a numeric character else a alphabetic character. To generate these characters the same function is called with the return string length as 1.
function generateRandomString($type,$Len)
{
$RndStr;
switch($type)
{
case 'NU':
for($i=0; $i<$Len; $i++)
{
$RndStr .= rand(0,9);
}
break;
case 'AN':
for($i=0; $i<$Len; $i++)
{
$RndStr .= (rand(0,1)>0?generateRandomString('NU',1):generateRandomString('AL',1));
}
break;
case 'AL':
for($i=0; $i<$Len; $i++)
{
$RndStr .= chr(rand(65,90));
}
break;
}
return $RndStr;
}
if you want to generate alphabetic string of lower case, you pass the return value to the function strtolower().
Victory attained by violence is tantamount to a defeat, for it is momentary.
—
Hi my name is Alfie. I am an IT professional specialized in opensource web development. I work as a System Analist com Web Programmer. My blog have no restriction on the topics it deals with but mainly specialized on infotainment topics. Your constant help, support and comments will be an encouragement for my efforts.