PHP之验证码

 1 <?php
 2     //开启session
 3     session_start();
 4 
 5     function getVerify($len = 4){
 6         //生成字符集数组
 7         $char_list = "qwertyuipasdfghjklzxcvbnm123456789QWERTYUIPASDFGHJKLZXCVBNM";    
 8         $char_list_len = strlen($char_list);
 9         //设置验证码长度
10         $code = '';
11         //for循环随机取出四个字符 ,进行拼接
12         for ($i=1; $i<=$len; $i++) { 
13             $rand_index = mt_rand(0, $char_list_len-1);
14             $code.=$char_list[$rand_index];
15         }
16 
17         // echo "$code";
18         //存入session中        
19         $_SESSION['verify'] = $code;
20 
21         //随机背景图片
22         $gb_img='./captcha/captcha_bg'.mt_rand(1, 5).'.jpg';
23         $image = imagecreatefromjpeg($gb_img);
24 
25         //随机产生字体的颜色
26         if (mt_rand(1,2) ==1  ) {
27             $font_color = imagecolorallocate($image,0,0,0); //黑色
28         }else{
29             $font_color = imagecolorallocate($image,255,255,255); //白色
30         }
31         
32         $font_size=5;
33 
34         //计算位置
35         //计算画布的宽和高
36         $img_w = imagesx($image);
37         $img_h = imagesy($image);
38         
39         //字体的宽和高
40         $font_w = imagefontwidth($font_size);
41         $font_h = imagefontheight($font_size);
42 
43         //字符串的宽和高
44         $char_w = $font_w*$len;
45         $char_h = $font_h;
46 
47         //得到最终验证码能够在图片的居中位置显示
48         $str_x = ($img_w-$char_w)/2;
49         $str_y = ($img_h-$char_h)/2;
50 
51         //把随机验证码填写到图片上
52         imagestring($image, $font_size, $str_x, $str_y, $code, $font_color);
53 
54         header("content-type:image/jpeg");
55         //输出到浏览器
56         imagejpeg($image);
57         //销毁图像资源
58         imagedestroy($image);
59     }
60     //测试
61     getVerify();

 

posted @ 2016-12-10 18:15  被时光移动的城市  阅读(330)  评论(0编辑  收藏  举报