---
title: "使用PHP生成验证码-面向对象方式"
author: "mmdev"
date: "2011-12-28T09:29:00Z"
tags: []
slug: "php"
draft: false
lastmod: "2012-03-08T22:49:57Z"
id: 1447158
url: "https://mmdev.iteye.com/blog/1447158"
---

使用PHP生成验证码图像大致需要以下几个步骤：

1、创建图片并填充背景

2、生成随机验证码

3、生成干扰线和雪花

4、生成验证码文字

5、输出

&lt;?php  
//验证码类  
class ValidateCode {  
//随机因子  
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';  
private $code;//验证码  
private $codelen = 4;//验证码长度  
private $width = 130;//宽度  
private $height = 50;//高度  
private $img;//图像资源句柄  
private $font;//字体  
private $fontcolor;//字体颜色  
private $fontsize = 20;//字体大小

public function \_\_construct(){  
$this-&gt;font = ROOT\_PATH.'/font/elephant.ttf';  
}

//生成验证码  
private function createCode(){  
$\_len = strlen($this-&gt;charset)-1;  
for ($i=0;$i&lt;$this-&gt;codelen;$i++) {  
$this-&gt;code .= $this-&gt;charset\[mt\_rand(0,$\_len)];  
}  
}

//生成背景  
private function createBg(){  
$this-&gt;img = imagecreatetruecolor($this-&gt;width, $this-&gt;height);  
$color = imagecolorallocate($this-&gt;img, mt\_rand(157,255), mt\_rand(157,255), mt\_rand(157,255));  
imagefilledrectangle($this-&gt;img,0,$this-&gt;height,$this-&gt;width,0,$color);  
}

//生成文字  
private function createFont(){  
$\_x = $this-&gt;width / $this-&gt;codelen;  
for ($i=0;$i&lt;$this-&gt;codelen;$i++) {  
$this-&gt;fontcolor = imagecolorallocate($this-&gt;img,mt\_rand(0,156),mt\_rand(0,156),mt\_rand(0,156));  
imagettftext($this-&gt;img,$this-&gt;fontsize,mt\_rand(-30,30),$\_x\*$i+mt\_rand(1,5),$this-&gt;height / 1.4,$this-&gt;fontcolor,$this-&gt;font,$this-&gt;code\[$i]);  
}  
}

//生成线条和雪花  
private function createLine(){  
for ($i=0;$i&lt;6;$i++) {  
$color = imagecolorallocate($this-&gt;img,mt\_rand(0,156),mt\_rand(0,156),mt\_rand(0,156));  
imageline($this-&gt;img,mt\_rand(0,$this-&gt;width),mt\_rand(0,$this-&gt;height),mt\_rand(0,$this-&gt;width),mt\_rand(0,$this-&gt;height),$color);  
}  
for ($i=0;$i&lt;100;$i++) {  
$color = imagecolorallocate($this-&gt;img,mt\_rand(200,255),mt\_rand(200,255),mt\_rand(200,255));  
imagestring($this-&gt;img,mt\_rand(1,5),mt\_rand(0,$this-&gt;width),mt\_rand(0,$this-&gt;height),'\*',$color);  
}  
}

//输出  
private function outPut(){  
header('Content-Type:image/png');  
imagepng($this-&gt;img);  
imagedestroy($this-&gt;img);  
}

//对外生成  
public function doimg(){  
$this-&gt;createBg();  
$this-&gt;createCode();  
$this-&gt;createLine();  
$this-&gt;createFont();  
$this-&gt;outPut();  
}

//获取验证码  
public function getCode(){  
return strtolower($this-&gt;code);  
}  
}

?&gt;

然后再写一个PHP文件调用这个类的方法

&lt;?php  
require substr(dirname(\_\_FILE\_\_), 0, -7).'/init.inc.php';  
$\_vc = new ValidateCode();  
$\_vc-&gt;doimg();  
$\_SESSION\['code'] = $\_vc-&gt;getCode();  
?&gt;

最后在页面上直接调用就可以了

&lt;img src="../config/code.php" onclick="javascript:this.src='../config/code.php?tm='+Math.random();" /&gt;