Skip to content

Instantly share code, notes, and snippets.

@darraghenright
Created February 15, 2012 09:15
Show Gist options
  • Save darraghenright/1834648 to your computer and use it in GitHub Desktop.
Save darraghenright/1834648 to your computer and use it in GitHub Desktop.
Simple ascii random string generator
<?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