Created
February 15, 2012 09:15
-
-
Save darraghenright/1834648 to your computer and use it in GitHub Desktop.
Simple ascii random string generator
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
<?php | |
function generateRandomString($length = 8) | |
{ | |
if (0 >= $length || !is_int($length)) { | |
$msg = sprintf('Exception! "%s()" only accepts positive integer values of 1 or more', __FUNCTION__); | |
throw new UnexpectedValueException($msg); | |
} | |
$ascii = array_merge( | |
range(48, 57), | |
range(65, 90), | |
range(97, 122) | |
); | |
$random = array(); | |
$limit = count($ascii) - 1; | |
while (0 !== ($length--)) { | |
$n = mt_rand(0, $limit); | |
$random[] = chr($ascii[$n]); | |
} | |
return implode($random); | |
} | |
// generate! | |
system('clear'); | |
define('RAND_LENGTH', 8); | |
try { | |
echo generateRandomString(RAND_LENGTH) . PHP_EOL; | |
} catch (UnexpectedValueException $e){ | |
echo $e->getMessage() . PHP_EOL; | |
exit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment