Created
November 21, 2012 23:00
-
-
Save eakmotion/4128407 to your computer and use it in GitHub Desktop.
PHP: random characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate and return a random characters string | |
* | |
* Useful for generating passwords or hashes. | |
* | |
* The default string returned is 8 alphanumeric characters string. | |
* | |
* The type of string returned can be changed with the "type" parameter. | |
* Seven types are - by default - available: basic, alpha, alphanum, num, nozero, unique and md5. | |
* | |
* @param string $type Type of random string. basic, alpha, alphanum, num, nozero, unique and md5. | |
* @param integer $length Length of the string to be generated, Default: 8 characters long. | |
* @return string | |
*/ | |
function random_str($type = 'alphanum', $length = 8) | |
{ | |
switch($type) | |
{ | |
case 'basic' : return mt_rand(); | |
break; | |
case 'alpha' : | |
case 'alphanum' : | |
case 'num' : | |
case 'nozero' : | |
$seedings = array(); | |
$seedings['alpha'] = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$seedings['alphanum'] = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$seedings['num'] = '0123456789'; | |
$seedings['nozero'] = '123456789'; | |
$pool = $seedings[$type]; | |
$str = ''; | |
for ($i=0; $i < $length; $i++) | |
{ | |
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); | |
} | |
return $str; | |
break; | |
case 'unique' : | |
case 'md5' : | |
return md5(uniqid(mt_rand())); | |
break; | |
} | |
} | |
/*======================================================+ | |
Usage Example: | |
--------------- | |
# Generate 10 chars. alphanumeric string | |
echo random_str('alphanum', 10); | |
# Generate 10 chars. alpha string | |
echo random_str('alpha', 10); | |
# Generate 10 chars. numeric string | |
echo random_str('num', 10); | |
# Generate 10 chars. nozero-numeric string | |
echo random_str('nozero', 10); | |
# Generate basic string | |
echo random_str('basic'); | |
# Generate unique string | |
echo random_str('unique'); | |
# Generate md5 string | |
echo random_str('md5'); | |
+======================================================*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment