一个粗糙的验证码类

 1 <?php
 2 //验证码类
 3 class ValidateCode {
 4      private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子
 5      private $code;//验证码
 6      private $codelen = 4;//验证码长度
 7      private $width = 130;//宽度
 8      private $height = 50;//高度
 9      private $img;//图形资源句柄
10      private $font;//指定的字体
11      private $fontsize = 20;//指定字体大小
12      private $fontcolor;//指定字体颜色
13 
14      //构造方法初始化
15      public function __construct() {
16       $this->font = dirname(__FILE__).'/Elephant.ttf';//注意字体路径要写对,否则显示不了图片
17      }
18 
19      //生成随机码
20      private function createCode() {
21       $_len = strlen($this->charset)-1;
22       for ($i=0;$i<$this->codelen;$i++) {
23        $this->code .= $this->charset[mt_rand(0,$_len)];
24       }
25      }
26 
27      //生成背景
28      private function createBg() {
29       $this->img = imagecreatetruecolor($this->width, $this->height);
30       $color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
31       imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);
32      }
33  //生成文字
34  private function createFont() {
35   $_x = $this->width / $this->codelen;
36   for ($i=0;$i<$this->codelen;$i++) {
37    $this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
38    imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]);
39   }
40  }
41  //生成线条、雪花
42  private function createLine() {
43       //线条
44       for ($i=0;$i<6;$i++) {
45        $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
46        imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
47       }
48       //雪花
49       for ($i=0;$i<100;$i++) {
50        $color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
51        imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
52       }
53      }
54      //输出
55      private function outPut() {
56       header('Content-type:image/png');
57       imagepng($this->img);
58       imagedestroy($this->img);
59      }
60 
61      //对外生成
62      public function doimg() {
63       $this->createBg();
64       $this->createCode();
65       $this->createLine();
66       $this->createFont();
67       $this->outPut();
68      }
69      
70      //获取验证码
71      public function getCode() {
72       return strtolower($this->code);
73      }
74 }
75 ?>

 

posted @ 2017-01-11 14:12  isykw  阅读(143)  评论(0编辑  收藏  举报