效果:
myvcode.class.php:封装创建验证码的类
<"mailto:*@param">*@param int $width 设置默认宽度
*@param int $height 设置默认高度
*@param int $codeNum 设置验证码中的字符个数
*@param int $pixNum 设置干扰点的个数
*@param int $lineNum 设置干扰线的数量
*/
function __construct($width=80,$height=40,$codeNum=4,$pixNum=40,$lineNum=5)
{
$this->width = $width;
$this->height = $height;
$this->codeNum = $codeNum;
$this->pixNum = $pixNum;
$this->lineNum = $lineNum;
}
/*内部私有方法,创建图像资源*/
private function getCreateImage()
{
$this->image = imagecreatetruecolor($this->width, $this->height);
$white = imagecolorallocate($this->image,0xff,0xff,0xff);
imagefill($this->image, 0, 0, $white);
$black = imagecolorallocate($this->image,0,0,0);
imagerectangle($this->image, 0, 0, $this->width-1, $this->height-1, $black);
}
/*内部私有方法,绘制字符,去掉o0Llz和012*/
private function createCheckCode()
{
$code = '3456789abcdefghijkmnpqrstuvwxyABCDEFGHIJKMNPQRSTUVWXY';
$this->checkCode = "";
for($i=0; $i<$this->codeNum;$i++)
{
$char = $code{rand(0,strlen($code) - 1)};
$this->checkCode .= $char;
$fontColor = imagecolorallocate($this->image, rand(0,128), rand(0,128),rand(0,128));
$fontSize = rand(3,5);
$x = rand(0,$this->width-imagefontwidth($fontSize));
$y = rand(0,$this->height-imagefontheight($fontSize));
imagechar($this->image, $fontSize, $x, $y, $char, $fontColor);
}
}
/*内部私有方法设置干扰元素*/
private function setDisturbColor()
{
/*绘制干扰点*/
for($i=0; $i<$this->pixNum; $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);
}
/*绘制干扰线*/
for($i=0; $i<$this->lineNum; $i++)
{
$color = imagecolorallocate($this->image, rand(0,255), rand(0,255), rand(0,255));
imageline($this->image, rand(1,$this->width / 2), rand(1,$this->height / 2),
rand($this->width / 2,$this->width – 2), rand($this->height / 2,$this->height – 2), $color);
}
}
/*开启session保存 利用echo 输出图像*/
function __toString()
{
$_SESSION['code'] = strtoupper($this->checkCode);
$this->getCreateImage();
$this->createCheckCode();
$this->setDisturbColor();
$this->outputImg();
}
/*内部私有方法输出图像*/
private function outputImg()
{
header("content-type:image/png");
imagepng($this->image);
}
/*析构方法,释放对象*/
function __destruct()
{
imagedestroy($this->image);
}
}
"htmlcode"><"htmlcode"><img src="/UploadFiles/2021-04-02/imgcode.php">可以加一个a标签,用js实现换一张效果:
/*局部刷新换验证码*/
function changeCode()
{
var imgcode = document.getElementById(‘code');
var change = document.getElementById(‘change');
change.onclick = function()
{
/*必须加后面的参数才能刷新*/
imgcode.src='code.php?tm'+Math.random();
}
}code和change分别是img和a的id
标签:PHP,图形验证码
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com
暂无“PHP制作图形验证码代码分享”评论...