经典的php验证码类,随笔记一下,以后用的上的时候方便查找。
封装的captcha.class.php
1 <?php 2 class captcha{ 3 private $width;//宽 4 private $height;//高 5 private $codeNum;//数量 6 private $code;//码 7 private $im;//图 8 9 function __construct($width=80, $height=20, $codeNum=4) 10 { 11 $this->width = $width; 12 $this->height = $height; 13 $this->codeNum = $codeNum; 14 } 15 16 function showImg() 17 { 18 //创建图片 19 $this->createImg(); 20 //设置干扰元素 21 $this->setDisturb(); 22 //设置验证码 23 $this->setCaptcha(); 24 //输出图片 25 $this->outputImg(); 26 } 27 28 function getCaptcha() 29 { 30 return $this->code; 31 } 32 33 private function createImg() 34 { 35 $this->im = imagecreatetruecolor($this->width, $this->height); 36 $bgColor = imagecolorallocate($this->im, 0, 0, 0); 37 imagefill($this->im, 0, 0, $bgColor); 38 } 39 40 private function setDisturb() 41 { 42 $area = ($this->width * $this->height) / 20; 43 $disturbNum = ($area > 250) ? 250 : $area; 44 //加入点干扰 45 for ($i = 0; $i < $disturbNum; $i++) { 46 $color = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255)); 47 imagesetpixel($this->im, rand(1, $this->width - 2), rand(1, $this->height - 2), $color); 48 } 49 //加入弧线 50 for ($i = 0; $i <= 5; $i++) { 51 $color = imagecolorallocate($this->im, rand(128, 255), rand(125, 255), rand(100, 255)); 52 imagearc($this->im, rand(0, $this->width), rand(0, $this->height), rand(30, 300), rand(20, 200), 50, 30, $color); 53 } 54 } 55 56 private function createCode() 57 { 58 $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ"; 59 60 for ($i = 0; $i < $this->codeNum; $i++) { 61 $this->code .= $str{rand(0, strlen($str) - 1)}; 62 } 63 } 64 65 private function setCaptcha() 66 { 67 $this->createCode(); 68 69 for ($i = 0; $i < $this->codeNum; $i++) { 70 $color = imagecolorallocate($this->im, rand(50, 250), rand(100, 250), rand(128, 250)); 71 $size = rand(floor($this->height / 5), floor($this->height / 3)); 72 $x = floor($this->width / $this->codeNum) * $i + 5; 73 $y = rand(0, $this->height - 20); 74 imagechar($this->im, $size, $x, $y, $this->code{$i}, $color); 75 } 76 } 77 78 private function outputImg() 79 { 80 if (imagetypes() & IMG_JPG) { 81 header('Content-type:image/jpeg'); 82 imagejpeg($this->im); 83 } elseif (imagetypes() & IMG_GIF) { 84 header('Content-type: image/gif'); 85 imagegif($this->im); 86 } elseif (imagetype() & IMG_PNG) { 87 header('Content-type: image/png'); 88 imagepng($this->im); 89 } else { 90 die("Don't support image type!"); 91 } 92 } 93 } 94 95 ?>
demo.php
1 <?php 2 session_start(); 3 require('captcha.class.php'); 4 $captcha = new captcha(80,20,4); 5 $code = $captcha->getCaptcha(); 6 $_SESSION['code'] = $code; 7 $captcha->showImg(); 8 ?>