一个不错的验证码函数
推荐一个不错的验证码函数
今天要用到验证码,表示自己关于图形库没仔细学,那就网上用别人造的轮子吧,以后自己也加进把图形库好好看看,省得以后再麻烦!
源码来自于emlog
效果图
下面是代码加详细解释:
function verify_code() {
$randCode = ''; //定义随机字符
$chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPRSTUVWXYZ23456789'; //需要用到的验证码字符,如需更多请自行添加
/* 随机生成5位字符的验证码字符 */
for ( $i = 0; $i < 5; $i++ ){
$randCode .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
$img = imagecreate(70,22); //画图
$bgColor = imagecolorallocate($img,255,255,255); //底色
$pixColor = imagecolorallocate($img,mt_rand(30, 180), mt_rand(10, 100), mt_rand(40, 250)); //设置字体随机换色
/* 将验证码字符陆续打印在图片上 */
for($i = 0; $i < 5; $i++){
$x = $i * 13 + mt_rand(0, 4) - 2;
$y = mt_rand(0, 3);
$text_color = imagecolorallocate($img, mt_rand(30, 180), mt_rand(10, 100), mt_rand(40, 250));
imagechar($img, 5, $x + 5, $y + 3, $randCode[$i], $text_color);
}
/* 为图片背景设置干扰元素 */
for($j = 0; $j < 60; $j++){
$x = mt_rand(0,70);
$y = mt_rand(0,22);
imagesetpixel($img,$x,$y,$pixColor);
}
$_SESSION['code'] = $randCode; //将验证码写入sssion
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img); //输出图像
}
代码简单易懂,效果也很漂亮,欢迎尝试!!