note 74468 added to function.rand
| From: | dxillusion at gmail dot com | Date: | Thu, 12 Apr 2007 17:50:29 +0000 |
| Subject: | note 74468 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125343@lists.php.net to get a copy of this message | ||
A very useful function for creating key with a lot of flexibility to control the type of characters
used in your key
you can add your custom type of character limitations to it by adding a custom preg_match according
to your liking
Enjoy
<?php
/**
* Key Generator
*
* @param int Length of the key
* @param string Type of Character
* (lower, upper, numeric, ALPHA, ALNUM)
*
* @return string Generated key from the arguments
*/
function mKey($len = 12, $type = 'ALNUM')
{
// Register the lower case alphabet array
$alpha = 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');
// Register the upper case alphabet array
$ALPHA = 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');
// Register the numeric array
$num = array('1', '2', '3', '4', '5',
'6', '7', '8', '9', '0');
// Initialize the keyVals array for use in the for loop
$keyVals = array();
// Initialize the key array to register each char
$key = array();
// Loop through the choices and register
// The choice to keyVals array
switch ($type)
{
case 'lower' :
$keyVals = $alpha;
break;
case 'upper' :
$keyVals = $ALPHA;
break;
case 'numeric' :
$keyVals = $num;
break;
case 'ALPHA' :
$keyVals = array_merge($alpha, $ALPHA);
break;
case 'ALNUM' :
$keyVals = array_merge($alpha, $ALPHA, $num);
break;
}
// Loop as many times as specified
// Register each value to the key array
for($i = 0; $i <= $len-1; $i++)
{
$r = rand(0,count($keyVals));
$key[$i] = $keyVals[$r];
}
// Glue the key array into a string and return it
return join("", $key);
}
?>
If you have any questions or comments feel free to contact me
----
Server IP: 69.147.83.197
Probable Submitter: 72.229.221.25
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/74468
Del: integrated -- https://master.php.net/note/delete/74468/integrated
Del: useless -- https://master.php.net/note/delete/74468/useless
Del: bad code -- https://master.php.net/note/delete/74468/bad+code
Del: spam -- https://master.php.net/note/delete/74468/spam
Del: non-english -- https://master.php.net/note/delete/74468/non-english
Del: in docs -- https://master.php.net/note/delete/74468/in+docs
Del: other reasons-- https://master.php.net/note/delete/74468
Reject -- https://master.php.net/note/reject/74468
Search -- https://master.php.net/manage/user-notes.php