<?php
//开启session,用来保存验证码
session_start();
/**
* 验证码的封装类
* @param $w int 验证码图像的宽
* @param $h int 验证码图像的高
* @param $cn int 验证码的位数
* @return $img resource 返回验证码图像资源
*/
class CheckCode{
//定义属性
private $width; //验证码图像的宽
private $height;//验证码图像的高
private $count;//验证码位数
//构造函数,初始化私有属性
function __construct($w,$h,$cn){
$this->width=$w;
$this->height=$h;
$this->count=$cn;
//echo $this->count;//验证传值
}
//得到随机字符,并存入session
function getCode(){
$string="0123456789abcdefghijklmnopqrstuvwxyz";
//如果要使用大写字母,可以使用函数来转换
//$stringU=strtoupper($string);
$code="";
for($i=0;$i<$this->count;$i++){
$code.=$string[rand(0, strlen($string)-1)];
}
$_SESSION['verify']=$code; //被其它页面调用来进行验证
return $code; //得到验证码字符串
}
//生成图像
function getCheckCode(){
header("content-type:p_w_picpath/gif");
$img=p_w_picpathcreate($this->width, $this->height);
$bgcolor=p_w_picpathcolorallocate($img, 255, 255, 255); //图像背景色
$strColor=p_w_picpathcolorallocate($img, 255, 0, 0);//验证码字符颜色
$fontfile="simsunb.ttf";//字体文件文件路径
$size=30; //字体大小
$angle=rand(-5, 5); //字体倾斜角度
//干扰元素的颜色
$color=p_w_picpathcolorallocate($img, 100, 100, 100);
//调用糙点函数
$this->createPix($img, $color);
//调用干扰线
$this->createLine($img,$color);
//写入字符到图像
p_w_picpathttftext($img, $size, $angle, 15, 50, $strColor, $fontfile, $this->getCode());
//输出图像
p_w_picpathgif($img);
//销毁内存中的缓存
p_w_picpathdestroy($img);
}
//对图像添加糙点
function createPix($p_w_picpath,$color){
for($i=0;$i<200;$i++){
p_w_picpathsetpixel($p_w_picpath, rand(0, $this->width), rand(0, $this->height), $color);
}
}
//添加干扰线
function createLine($p_w_picpath,$color){
for($i=0;$i<10;$i++){
p_w_picpathline($p_w_picpath, rand(0, $this->width), rand(0, $this->height),rand(0, $this->width), rand(0, $this->height), $color);
}
}
}
//调用方法如下
//实例化类的时候自动调用构造函数
$cc = new CheckCode(150, 80, 5);
$cc->getCheckCode();封装好的简单验证码类(带注释)
原创
©著作权归作者所有:来自51CTO博客作者jaty0817的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:封装好的图像缩放函数
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
生成验证码-超简单
轻松应对验证挑战:简单验证码的实现方法!
验证码 Java -
Java生成普通图片验证码和带数字计算的图片验证码,可直接打包集成到项目中
Java生成普通图片验证码和带数字计算的图片验证码
Image 验证码 图片验证码 -
简单的验证码程序
验证码
Python 验证码 验证程序
















