Random String Generator
Views Today: 1, Total Views: 3739, Submitted by: anjanesh on 20-06-2006
Generating a Random String: This is actually a very simple function that generates a random string.
Three constants are defined RAND_NUMBERS, RAND_LETTERS_LOWER and RAND_LETTERS_UPPER set to 1, 2 and 4 respectively - all being powers of 2. This was done so that it'll be easier when using a combination of these values.
Code
<?php
define("RAND_NUMBERS" , 1);
define("RAND_LETTERS_LOWER" , 2);
define("RAND_LETTERS_UPPER" , 4);
echo "Random Type 3 : <b>".GenerateRandom(RAND_LETTERS_LOWER + RAND_NUMBERS, 10)."</b><br/>";
echo "Random Type 7 : <b>".GenerateRandom(7, 10)."</b><br/>";
?>
<?php
/*
Parameters : $Type, $NoOfChars
$Type : Type of Random String
1 - Numbers, 2 - Small Letters, 3 - Capital Letters
For a combination of the above add the numbers - example : 5 - Small Letters and Capital Letters
A total of 7 possible values - 1 to 7
$NoOfChars : Number of characters for Random String
Returns Random String
*/
function GenerateRandom($Type, $NoOfChars)
{
$strList = array();
# Convert to binary format and find out what combination of random characters are required
$Binary_Equivalent = base_convert($Type, 10, 2);
# Loop through the bits
for ($i = strlen($Binary_Equivalent) - 1; $i >= 0; $i--)
{
if ($Binary_Equivalent[$i] == 1) # If the bit is 1 then add the characters to the character list
{
switch (pow(2, strlen($Binary_Equivalent) - $i - 1))
{
default;
case RAND_NUMBERS: # 2 ^ 0 = 1
$Ascii_Range = array(48, 57); # Numbers - Characters 0 to 9
break;
case RAND_LETTERS_LOWER: # 2 ^ 1 = 2
$Ascii_Range = array(97, 122); # Small Letters - Characters a to z
break;
case RAND_LETTERS_UPPER: # 2 ^ 2 = 4
$Ascii_Range = array(65, 90); # Capital Letters - Characters A to Z
break;
}
for ($j = $Ascii_Range[0]; $j <= $Ascii_Range[1]; $j++)
$strList[] = chr($j); # Add characters to array
}
}
$RndString = "";
for ($i = 0; $i < $NoOfChars; $i++)
$RndString .= $strList[rand(0, count($strList) - 1)];
return $RndString;
}
?>
You can spend time debugging it to get the idea of this binary method - after all there are only 7 possible ways - so debugging it 7 times is no biggie !
User Comments
If you want to comment on this tutorial you must first register or login.
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/cinedict/public_html/tutorialdash/tutorialview.php on line 287
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/cinedict/public_html/tutorialdash/tutorialview.php on line 287
Actually, you\'ll find most of the standard funtions out there implement the binary method.
Post A Comment
Fill out the following form to comment on this tutorial.



Syndicate
Its a bit confusing - not ideal for the beginner user. May be useful for more experienced users though.