验证码类
<?php
ob_clean();
header("Content-type:image/gif");
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-1,$this->height-1,$border);
}
private function createCheckCode()
{
for($i=0;$i<$this->codeNum;$i++)
{
$number=rand(0,2);
switch($number)
{
case 0:$rand_number=rand(48,57);break;
case 1:$rand_number=rand(65,90);break;
case 2:$rand_number=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;
$y=rand(0,$this->height-15);
imagechar($this->image,5,$x,$y,$this->checkCode[$i],$bg_color);
}
}
private function outputImage()
{
ob_clean();
imagegif($this->image);
}
function __destruct()
{
imagedestroy($this->image);
}
}
?>
Make 对象
<?php
session_start();
require_once('image.php');
$image=new ValidationCode(60,20,4);
$image->showImage();
$_SESSION['validationcode']=$image->getCheckCode();
?>
主文件
<?php
session_start();
if(isset($_POST['submit']))
{
if(trim($_POST["test"])==$_SESSION['validationcode'])
{
echo'提交成功';
}
else
{
echo '<font color="red">验证码输入错误!!</font>';
}
}
?>
<html>
<head>
<title>Image</title>
<meta http-equiv="content-type" content="text/html;charse=gb2312">
<script>
function newgdcode(obj,url)
{
obj.src=url+'?nowtime='+new Date().getTime();
}
</script>
</head>
<body>
<img src="makeCode.php" alt="看不清楚,换一张" style="cursor:pointer;" οnclick="javascript: newgdcode(this,this.src);"> //调个javascript重载
<form method="POST" action="make.php"> //PHP可以这么自己调自己
<input type="text" name="test"><br>
<input type="submit" name="submit" value="提交">
</form>
</body>
</html>