php——验证码生成类

本文详细介绍了PHP中验证码类的实现方式,包括构造函数、显示验证码图片、生成验证码字符、设置干扰像素等功能,旨在提供一种动态获取验证码图片和验证字符串的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
/*
 * Created on 2013-7-19
 *
 * 验证码类
 * 通过类的对象可以动态获取验证码图片和验证正码字符串。
 */

class ValidationCode{
	private $width;//图片宽度
	private $height;//图片高度
	private $codeNum;//字符个数
	private $checkCode;//验证码字符
	private $image;//验证码画布
	/**
	 * 构造函数
	 */
	function __construct($width=60,$height=20,$codeNum=4){
		$this->width=$width;
		$this->height=$height;
		$this->codeNum=$codeNum;
		$this->checkCode=$this->createCheckCode();
	}
	/**
	 * 显示并向浏览器输出图像
	 */
	function showImage(){
		$this->getCreateImage();//初始化画布
		$this->outputText();//向图像写入随机字符
		$this->setDisturbColor();//向图像添加一些干扰像素
		$this->outputImage();//生成相应格式的图像,并输出
	}

	function getCheckCode(){
		return $this->checkCode;
	}
	/**
	 * 创建图像
	 */
	private function getCreateImage(){
		$this->image=imagecreate($this->width,$this->height);
		$back=imagecolorallocate($this->image,255,255,255);
		$border=imagecolorallocate($this->image,0,0,0);
		imagerectangle($this->image,0,0,$this->width,$this->height-1,$border);
	}
	/**
	 * 生成验证码
	 */
	private function createCheckCode(){
		for($i=0;$i<$this->codeNum;$i++){
			$number=mt_rand(0,2);
			switch($number){
				case 0:$rand_number=mt_rand(48,57);break;//数字
				case 1:$rand_number=mt_rand(65,90);break;//大写字母
				case 2:$rand_number=mt_rand(97,122);break;//小写字母
			}
			$ascii=sprintf("%c",$rand_number);
			$ascii_number=$ascii_number.$ascii;
		}
		return $ascii_number;
	}
	/**
	 * 设置干扰像素
	 */
	private function setDisturbColor(){
		for($i=0;$i<100;$i++){
			$color=imagecolorallocate($this->image,rand(0,255),rand(0,255),rand(0,255));
			imagesetpixel($this->image,rand(1,$this->width-2),rand(1,$this->height-2),$color);
		}
	}
	/**
	 * 将验证码写在画布上
	 */
	private function outputText(){
		for($i=0;$i<$this->codeNum;$i++){
			$bg_color=imagecolorallocate($this->image,rand(0,255),rand(0,128),rand(0,255));
			$x=floor($this->width/$this->codeNum)*$i+3;//x轴位置的算法
			$y=rand(0,$this->height-15);
			imagechar($this->image,5,$x,$y,$this->checkCode[$i],$bg_color);
		}
	}
	/**
	 * 按照GD库生成的格式输出图像
	 */
	private function outputImage(){
		if(imagetypes()&IMG_GIF){
			header("Content-type:image/gif");
			imagegif($this->image);
		}else if(imagetypes()&IMG_JPG){
			header("Content-type:image/jpg");
			imagejpeg($this->image);
		}else if(imagetypes()&IMG_PNG){
			header("Content-type:image/png");
			imagepng($this->image);
		}else if(imagetypes()&IMG_WBMP){
			header("Content-type:image/vnd.wap.wbmp");
			imagewbmp($this->image);
		}else{
			die("php不支持图像创建!");
		}
	}
	/**
	 * 析构函数,释放图像所占内存
	 */
	function __destruct(){
		imagedestroy($this->image);
	}
}
//验证
$image=new ValidationCode(60,20,4);
$image->showImage();
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值