<?php session_start(); // //验证码的类(面向对象方式实现) //两个功能:1.将验证码作为图片进行输出工作。 // 2.把验证码保存到session中去。 // /*验证码模块所需要的几个步骤 1.背景。2.干扰。3.文字。4.输出。5.释放资源。 */ class Code{ public $img; //画布资源 public $width; //验证码画布的宽 public $height; //验证码画布的高 public $length; //验证码的位数 public $words; //验证码的文字,这一个成员属性用于保存到session中去。 //也用于将次文字输出到画布上。 //构造方法 给成员属性赋初值 function __construct($width,$height,$length){ $this->width = $width; $this->height = $height; $this->length = $length; } //出口程序 function pringImg(){ $this->bg(); //背景 $this->disturb(); //干扰 $this->setCode(); //产生文字 $this->printWord(); //文字添加进画布 $this->outImg(); //输出 } //创建背景方法 private function bg(){ $this->img = imagecreatetruecolor($this->width,$this->height); $bg_color = imagecolorallocate($this->img,rand(200,255),rand(200,255),rand(200,255)); imagefill($this->img,0,0,$bg_color); } //干扰项 private function disturb(){ for($i=0;$i<100;$i++){ //随机100个点 $color = imagecolorallocate($this->img,rand(0,150),rand(0,150),rand(0,150)); imagesetpixel($this->img,rand(0,$this->width),rand(0,$this->height),$color); }; for($i=0;$i<10;$i++){ //随机10条 $color = imagecolorallocate($this->img,rand(0,150),rand(0,150),rand(0,150)); imageline($this->img,rand(0,$this->width),rand(0,$this->height-5),rand(0,$this->width),rand(0,$this->height-10),$color); }; } //添加文字部分(生成验证码文字4位) private function setCode(){ $code = "1234567890abcdefghijklmnopqrstuvwxyz"; for($i=0;$i<$this->length;$i++){ //循环随机从code里面取字母 $this->words.=substr($code,rand(0,strlen($code)-1)); } $_SESSION['vcode']=$this->words; } //将验证码文字在图片上输出 private function printWord(){ for($i=0;$i<$this->length;$i++){ //在画布上生成随机文字 $x = ($this->width/$this->length)*$i+5; $y = rand(5,10); $font = 5; $code = substr($this->words,$i,1); $color = imagecolorallocate($this->img,rand(0,200),rand(0,200),rand(0,200)); imagestring($this->img,$font,$x,$y,$code,$color); } } //输出 private function outImg(){ header("Content-Type:image/png"); imagepng($this->img); } //释放资源 function __destruct(){ imagedestroy($this->img); } }