Skip to content

Instantly share code, notes, and snippets.

@WenLiangTseng
Last active December 21, 2015 10:19
Show Gist options
  • Save WenLiangTseng/6291480 to your computer and use it in GitHub Desktop.
Save WenLiangTseng/6291480 to your computer and use it in GitHub Desktop.
產生隨機字串
<?php //reference: http://stackoverflow.com/questions/5438760/generate-random-5-characters-string
function get_token( $length ) {
$seed = str_split(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, $length) as $k) $rand .= $seed[$k];
return $rand;
}
//usage example;
echo get_token(5);
//另一種方式,參考 http://stackoverflow.com/questions/4356289/php-random-string-generator
function generateRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo generateRandomString(8);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment