Skip to content

Instantly share code, notes, and snippets.

@xdstack
Created September 13, 2012 10:00
Show Gist options
  • Save xdstack/3713330 to your computer and use it in GitHub Desktop.
Save xdstack/3713330 to your computer and use it in GitHub Desktop.
PHP 生成随机字符串
function genRandomString() {
// 验证码的长度
$length = 10;
// 验证码包含的字符
$characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
$string = '';
// 获取 $characters 的长度,并随机截取其中一个字符,直到验证码的长度达到 10 个字符
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
// 返回生成的验证码
return $string;
}
@xdstack
Copy link
Author

xdstack commented Sep 13, 2012

在编写一套登录系统的时候,我们常常需要生成一个由随机字符组成的验证码。这个并不难,我们可以用拆分字符串的方法来生成随机字符串作为验证码。

这里用到了 mt_rand() 函数来生成随机整数,效率比用 rand() 高 4 倍。

来源:http://www.codecto.com/2010/12/php-random-string-with-numbers-and-letters/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment