1 <?php
2 //所有可能出现的字符
3 $chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
4 $chars_len = strlen($chars);
5 $code_len = 6;//码值的长度
6 $code = '';//初始化码值
7 for($i=1;$i<=$code_len;++$i){
8 $rand_index = mt_rand(0,$chars_len-1); //用mt_rand函数来生成随机数
9 $code.=$chars[$rand_index];
10 }
11 // echo $code;
12 //存储于session,用于验证
13 session_start();
14 $_SESSION['captcha_code'] = $code;
15
16 //背景图
17 $bg_file = './captcha/captcha_bg'.mt_rand(1,5).'.jpg';
18 //基于jpg格式的图片创建画布
19 $img = imageCreateFromJPEG($bg_file);
20
21 //随机分配字符串的颜色
22 $str_color = mt_rand(1,2) == 1 ? imageColorAllocate($img,0,0,0) : imageColorAllocate($img,0xff,0xff,0xff);
23 //字符串映在图片上
24 $font = 5;
25 //画布的尺寸
26 $img_w = imagesx($img);
27 $img_h = imagesy($img);
28 //字体的尺寸
29 $font_w = imagefontwidth($font);
30 $font_h = imagefontheight($font);
31 //字符串的尺寸
32 $code_w = $font_w*$code_len;
33 $code_h = $font_h;
34 $x = ($img_w-$code_w)/2;
35 $y = ($img_h-$code_h)/2;
36 imagestring($img, $font, $x, $y, $code, $str_color);
37 //输出
38 header('Content-Type: image/jpeg;');
39 imageJPEG($img);
40 //销毁
41 imagedestroy($img);
42
43 /**
44 *验证
45 *@param $request_code 用户表单提交的码值
46 *@return bool 是否匹配
47 */
48 public function checkCaptcha($request_code){
49 @session_start();
50 $result = isset($request_code)&&isset($_SESSION['captcha_code'])&&(strCaseCmp($request_code,$_SESSION['captcha_code'])==0);
51 //为了安全考虑 销毁session中的值
52 unset($_SESSION['captcha_code']);
53 return $result;
54 }