PHP制作图形验证码代码分享

时间:2021-05-26

效果:

myvcode.class.php:封装创建验证码的类

<?php
/*
* file:myvcode.class.php
* 验证码类,类名Vcode
*/
class Vcode
{
private $width;
private $height;
private $codeNum;
private $checkCode;
private $image;
private $pixNum;
private $lineNum; /*
*构造方法实例化验证码对象,并初始化数据
*@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);
}

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);}
}

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);
}
}
?>

imgcode.php输出图像

<?phpsession_start();require_once('myvcode.class.php');echo new Vcode();?>

test.html:同过img标签引用

<img src="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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章