<?php
class ValidateCode{ public $charset="abcdefghjkmnpqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789"; public $codelength=9;//验证码长度 public $code;//验证码 public $img;//画布 public $width; public $height; public $fontttf='SIMSUN.TTC';//字体可从C:\WINDOWS\Fonts下复制 public $fontSize=40; //生成随机验证码 public function createCode(){ $length=strlen($this->charset); for($i=0;$i<$this->codelength;$i++){ $this->code.=$this->charset[mt_rand(0,$length-1)]; } return $this->code; } //创建画布 public function createBg(){ header('Content-Type:image/png'); $this->img=imagecreatetruecolor($this->width,$this->height); $white=imagecolorallocate($this->img, 255, 255, 255); //填充背景(白色) imagefill($this->img, 0, 0, $white); //干扰线 for($i=0;$i<6;$i++){ $linecolor=imagecolorallocate($this->img, rand(50, 200), rand(100, 200), rand(150, 200)); imagearc($this->img,mt_rand(-$this->width,$this->width),mt_rand(-$this->height,$this->height),mt_rand(30,$this->width*2),mt_rand(20,$this->height*2),mt_rand(0,360),mt_rand(0,360),$linecolor); } //干扰点 for($i=0;$i<100;$i++){ $charcolor=imagecolorallocate($this->img, rand(200, 250), rand(200, 250), rand(200, 250)); imagechar($this->img, $this->fontSize, rand(0,$this->width), rand(0,$this->height), '*', $charcolor); } //验证码插入图片 imagefttext($this->img, $this->fontSize, 0, 4, $this->fontSize+3, imagecolorallocate($this->img, rand(0, 100), rand(0, 150), rand(0, 200)), $this->fontttf,$this->code); imagepng($this->img); imagedestroy($this->img); } //返回验证码 public function getCode(){ return $this->code; } //验证函数 public function checkCode(){ !$this->width && $this->width= $this->codelength*$this->fontSize*4/5 +5; !$this->height && $this->height=$this->fontSize+10; $this->createCode(); $this->createBg(); } }?>将上面的代码复制保存为ValidateCode.php
新建一个code.php文件,代码如下
<?php require './ValidateCode.php';session_start();$code=new ValidateCode();$code->codelength=5;//验证码数量$code->fontSize=20;//验证码大小$code->checkCode();$_SESSION['code']=strtolower($code->getCode());//将验证码保存到session中?>
在html中引入验证码图片,可点击图片刷新验证码
<html> <img src="code.php" οnclick="this.src='code.php?'+Math.random()"/></html>
结果如下