Created
January 28, 2013 13:54
-
-
Save hejrobin/4655653 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
/** | |
* random_string | |
* | |
* Generates random string based on character pool and length. | |
* | |
* @param string $type Return string type. | |
* @param int $length Return string length. | |
* | |
* @return string | |
*/ | |
function random_string(String $type = null, Integer $length = null) { | |
// Set default type value | |
if(is_null($type) === true) { | |
$type = 'alnum'; | |
} | |
// Set default length value | |
if(is_null($length) === true) { | |
$length = 0; | |
} | |
// Unique random string | |
$char_pool_unique = sha1(uniqid(mt_rand())); | |
// Numeric characters | |
$char_pool_numeric = '0123456789'; | |
// Numeric character without zeroes | |
$char_pool_nozero = substr($char_pool_numeric, 1); | |
// Lowercase alphabetic characters | |
$char_pool_alpha = 'abcdefghijklmnopqrstuvwxyz'; | |
// Uppercase alphabetic characters | |
$char_pool_alpha_uppercase = strtoupper($char_pool_alpha); | |
// Salt characters | |
$char_pool_salt = '!@#$%^&*()_+=-{}][;";/?<>.,'; | |
// Create unique string | |
if($type === 'unique') { | |
return $char_pool_unique; | |
} else { | |
// Handle character pools | |
switch ($type) { | |
case 'alnum' : | |
$char_pool = $char_pool_alpha . $char_pool_alpha_uppercase . $char_pool_numeric; | |
break; | |
case 'alnum.lowercase' : | |
$char_pool = $char_pool_alpha . $char_pool_numeric; | |
break; | |
case 'alnum.uppercase' : | |
$char_pool = $char_pool_alpha_uppercase . $char_pool_numeric; | |
break; | |
case 'numeric' : | |
$char_pool = $char_pool_numeric; | |
break; | |
case 'numeric.nozero' : | |
$char_pool = $char_pool_nozero; | |
break; | |
case 'salt' : | |
$char_pool = $char_pool_unique. $char_pool_salt; | |
break; | |
} | |
$random_string = ''; | |
// Generate random string based on char pool | |
for($n = 0; $n < $length; $n++) { | |
$random_string .= substr($char_pool, mt_rand(0, strlen($char_pool) -1), 1); | |
} | |
return $random_string; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment