本类的改写来自http://www.oschina.net/code/snippet_106025_6280,测试可用。
目的:类生成验证码之后将验证码的数字存session,之后可以通过内置的函数getCode(),取出验证的数字,直接用于判断验证码是否一致。
原类参考上面的链接:
修改后的类:
<?php class Captcha { private $width; private $height; private $codeNum; private $code; private $im; function __construct($width=80, $height=20, $codeNum=4) { $this->width = $width; $this->height = $height; $this->codeNum = $codeNum; } function showImg() { //创建图片 $this->createImg(); //设置干扰元素 $this->setDisturb(); //设置验证码 $this->setCaptcha(); //输出图片 $this->outputImg(); $_SESSION['veri_code']=$this->code; } function getCode(){ return $_SESSION['veri_code']; } function getCaptcha() { return $this->code; } private function createImg() { $this->im = imagecreatetruecolor($this->width, $this->height); $bgColor = imagecolorallocate($this->im, 0, 0, 0); imagefill($this->im, 0, 0, $bgColor); } private function setDisturb() { $area = ($this->width * $this->height) / 20; $disturbNum = ($area > 250) ? 250 : $area; //加入点干扰 for ($i = 0; $i < $disturbNum; $i++) { $color = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255)); imagesetpixel($this->im, rand(1, $this->width - 2), rand(1, $this->height - 2), $color); } //加入弧线 for ($i = 0; $i <= 5; $i++) { $color = imagecolorallocate($this->im, rand(128, 255), rand(125, 255), rand(100, 255)); imagearc($this->im, rand(0, $this->width), rand(0, $this->height), rand(30, 300), rand(20, 200), 50, 30, $color); } } private function createCode() { $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ"; for ($i = 0; $i < $this->codeNum; $i++) { $this->code .= $str{rand(0, strlen($str) - 1)}; } } private function setCaptcha() { $this->createCode(); for ($i = 0; $i < $this->codeNum; $i++) { $color = imagecolorallocate($this->im, rand(50, 250), rand(100, 250), rand(128, 250)); $size = rand(floor($this->height / 5), floor($this->height / 3)); $x = floor($this->width / $this->codeNum) * $i + 5; $y = rand(0, $this->height - 20); imagechar($this->im, $size, $x, $y, $this->code{$i}, $color); } } private function outputImg() { if (imagetypes() & IMG_JPG) { header('Content-type:image/jpeg'); imagejpeg($this->im); } elseif (imagetypes() & IMG_GIF) { header('Content-type: image/gif'); imagegif($this->im); } elseif (imagetype() & IMG_PNG) { header('Content-type: image/png'); imagepng($this->im); } else { die("Don't support image type!"); } } }
其实只需要在showImg() 方法最后存session,然后添加getCode()方法,其中取出session即可。
不过要取出session的时候还需要再次new这个类。
laravel5.2 下 测试代码如下(注意,在laravel中由于该验证码类为外部引入,需要 new \ClassName,否则报错):
类需要被引入:
require_once 'public/org/code/Code.class.php';
/** * 生成验证码 */ public function veriCode(){ $captcha = new \Captcha(80,30,4); $captcha->showImg();die(); }
/** * 获取当前验证码 */ public function getCode(){ $captcha = new \Captcha(80,30,4); echo $captcha->getCode();die(); }