怎么用原生php做验证码

如题所述

第1个回答  2015-06-29
<?php
class validateCode{
private $charset='abcdefghijhklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ23456789'; //随机因子
private $_len;
private $code; //验证码
private $codelen=4; //验证码长度
private $width=130; //画布宽度
private $height=50; //画布长度
private $img; //图形资源句柄
private $font; //制定字体
private $fontsize=26;//字体大小
private $fontcolor; //字体颜色

//初始化构造函数
public function __construct(){
$this->font=dirname(__file__).'/validateFont.ttf';
//字体文件及路径,__file__表示当前PHP文件绝对路径,dirname表示这个PHP文件的绝对路径的上一层
}

//生成随机码
private function createCode(){
$this->_len=strlen($this->charset)-1; //strlen表示计算字符串长度
for($i=1;$i<=$this->codelen;$i++){
$this->code.=$this->charset[mt_rand(0,$this->_len)];
}
}
//生成背景
private function createBG(){
$this->img=imagecreatetruecolor($this->width,$this->height);//创建图像
$color=imagecolorallocate($this->img,mt_rand(157,255),mt_rand(157,255),mt_rand(157,255)); //分配颜色函数(红,绿,蓝)
imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color); //矩形区域着色函数(要填充的图像,x1,y1,x2,y2,要填充的颜色),x1,y1,x2,y2表示矩形的对角线
}

//生成文字
private function createFont(){
$_x=$this->width/$this->codelen;
for($i=0;$i<$this->codelen;$i++){
$this->fontcolor=imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height/1.4,$this->fontcolor,$this->font,$this->code[$i]); //参数 size 为字形的尺寸;angle 为字型的角度,顺时针计算,0 度为水平,也就是三点钟的方向 (由左到右),90 度则为由下到上的文字;x,y 二参数为文字的坐标值 (原点为左上角);参数 col 为字的颜色;fontfile 为字型文件名称,亦可是远端的文件;text 当然就是字符串内容了。
}
}

//生成线条雪花
private function createLine(){
//线条
for($i=0;$i<6;$i++){
$color=imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}

//雪花
for($i=0;$i<40;$i++){
$color=imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
}
}

//输出
private function outPut(){
header("content-type:image/png");
imagepng($this->img);
imagedestroy($this->img);
}

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

//获取验证码
public function getCode(){
return strtolower($this->code);
}
}
?>
字体自己去找,修改下路径就行了