PHP生成验证码的类

新建一个PHP文件,包含生成验证码的类,名为:Verify.class.php 该文件需要配合一个名为:"bgs"的图片文件使用,里面包含了验证码的背景图片,最好大小一致,背景相似。

上代码,里面有一个类,名为:Verify

<?php 
//验证码
/*
* 1、背景(浅色、颜色随机)
* 2、干扰(点、线)
* 3、文字
*/
class Verify{
public $config = array(
'width' => 80,
'height' => 30,
'length' => 4,
'type'=>3
);
private $img; //GD资源
private $string; //验证码字库

function __construct($config=array()){
$this->config = array_merge($this->config,$config);
//完成初始化工作。
$this->getString($this->config['type']);
}

//完成验证码的背景布
private function getBg(){
//1、从bgs目录随机获取一张图片
$bgPath = './bgs';
$dir = opendir($bgPath);
while(($filename=readdir($dir))!==false){
if($filename!='.'&&$filename!='..'){
$bgs[] = $filename;
}
}
closedir($dir);
$filename = $bgPath.'/'.$bgs[array_rand($bgs)];
//2、将随机取得的图片转换为合适的尺寸
//   缩放图片
$this->img = imagecreatetruecolor($this->config['width'],$this->config['height']);
$src_img = imagecreatefromjpeg($filename);
list($src_w,$src_h)=getimagesize($filename);

imagecopyresampled($this->img,$src_img,
                   0,0,0,0,
                   $this->config['width'],$this->config['height'],
                   $src_w,$src_h);
imagedestroy($src_img);

}

//干扰
private function distrub(){
$maxWidth = $this->config['width']-1;
$maxHeight = $this->config['height']-1;
for($i=0;$i<100;$i++){
$color = imagecolorallocate($this->img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
imagesetpixel($this->img,mt_rand(1,$maxWidth),mt_rand(1,$maxHeight),$color);
}
for($i=0;$i<10;$i++){
$color = imagecolorallocate($this->img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
imageline($this->img,mt_rand(1,$maxWidth),mt_rand(1,$maxHeight),mt_rand(1,$maxWidth),mt_rand(1,$maxHeight),$color);
}
}

public function entry(){
session_start();
$this->getBg();
//$this->distrub();
//文字
$font = 5;
$sWord = '';
for($i=0;$i<$this->config['length'];$i++){
$x = ($this->config['width']/$this->config['length'])*$i+5;
$y = mt_rand(5,10);
$code = substr($this->string,mt_rand(0,strlen($this->string)-1),1);
$sWord.= $code;
$color = imagecolorallocate($this->img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
imagestring($this->img,$font,$x,$y,$code,$color);
}
$_SESSION['vcode'] = $sWord;

header('Content-Type:image/png');
imagepng($this->img);
imagedestroy($this->img);
}

private function getString($type){
switch($type){
case 1:
      $this->string = "0126456789";
       break;
case 2:    
  $this->string = "abcdefghijklmnopqrstuvwxyz";
  break;
case 3:  
      $this->string = "0126456789abcdefghijklmnopqrstuvwxyz";
      break;
}
}
}

//创建一个Verify实例,调用entry(),就可以实现验证码,并且上述案例将验证码存入了session更方便做验证
$v = new Verify;
$v->entry();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值