实现验证码类 vcode.class.php
<?php
class Vcode
{
private $width;
private $height;
private $num;
private $code;
private $im;
function __construct($width=80,$height=25,$num=4)
{
$this->width = $width;
$this->height = $height;
$this->num = $num;
$this->code = $this->createCode();
}
function getCode(){
return $this->code;
}
function outimg(){
$this->createBg();
$this->outString();
$this->setDisturbElement();
$this->printImg();
}
private function createBg(){
$this->im = imagecreatetruecolor($this->width,$this->height);
$bgColor = imagecolorallocate ( $this->im, rand(225,255), rand(225,255), rand(225,255) );
imagefill ( $this->im , 0 , 0 , $bgColor );
$borderColor = imagecolorallocate($this->im,0,0,0);
imagerectangle ( $this->im , 0 , 0 , $this->width-1 , $this->height-1 , $borderColor );
}
private function outString(){
for ($i=0; $i < $this->num; $i++) {
$textColor = imagecolorallocate ( $this->im , rand(0,128) , rand(0,128) , rand(0,128) );
$fontsize = rand(10,16);
$x = 3+($this->width/$this->num)*$i;
$y = rand(imagefontheight($fontsize),$this->height-2)-3;
imagechar( $this->im , $fontsize , $x , 3 , $this->code{$i}, $textColor );
}
}
private function setDisturbElement(){
for ($i=0; $i < 100; $i++) {
$dotColor = imagecolorallocate ( $this->im , rand(0,255) , rand(0,255) , rand(0,255) );
imagesetpixel($this->im, rand(1,$this->width-2), rand(1,$this->height-2), $dotColor);
}
for ($i=0; $i < 10; $i++) {
$lineColor = imagecolorallocate ( $this->im , rand(0,255) , rand(0,255) , rand(0,255) );
imagearc($this->im, rand(-10,$this->width), rand(-10,$this->height+10), rand(30,300), rand(30,300), 55, 44, $lineColor);
}
}
private function printImg(){
header("Content-type:text/png");
imagepng($this->im);
}
private function createCode(){
$code = '';
$codes = '3456789abcdefjhijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXY';
for ($i=0; $i < $this->num; $i++) {
$code .= $codes{rand(0,strlen($codes)-1)};
}
return $code;
}
function __destruct(){
imagedestroy($this->im);
}
}
?>
05-code.php
<?php
session_start();
include 'vcode.class.php';
$vcode = new Vcode(80,25,4);
$_SESSION['code'] = $vcode->getCode();
$vcode->outimg();
?>
05-reg.php
<?php
session_start();
if(isset($_POST['dosubmit'])){
if(strtolower($_POST['code']) === strtolower($_SESSION['code'])){
echo "验证码输入正确<br/>";
}else{
echo "验证码输入错误<br/>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="05-reg.php" method="post">
username: <input type="text" name="username"> <br/>
password: <input type="password" name="password"><br/>
code: <input type="text" name="code"><img onclick="this.src='05-code.php?'+Math.random()" src="05-code.php"><br/>
<input type="submit" name="dosubmit" value="登 录">
</form>
</body>
</html>