看了网上的例子,根据自己的想法写了一个生成验证码的类。
- createverify.class.php
<?php
/**
* 验证码类
* @author hui
* $width->验证码宽度
* $height->验证码高度
* $str->字符因子
* $font->字体名字及路径
*/
class Createverify{
private $img;
private $img_width;
private $img_height;
private $img_bgc;
private $str;
private $code_content;
private $code_color;
private $code_font;
public function __construct($width,$height,$str,$font){
$this->img_width=$width;
$this->img_height=$height;
$this->str=$str;
$this->code_font=$font;
$this->Get_code();
$this->Session_code();
}
//生成验证码图片
public function Get_img(){
$this->img=imagecreate($this->img_width,$this->img_height);
$this->img_bgc=imagecolorallocate($this->img,255,255,255);
$this->Get_pixle();
$this->Get_line();
$x=5;
foreach ($this->code_content as $key) {
$this->code_color = imagecolorallocate($this->img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagettftext($this->img,mt_rand(16,24), mt_rand(-15,15),$x,mt_rand(22,32), $this->code_color,$this->code_font,$key);
$x+=24;
}
header('Content-type:image/png');
imagepng($this->img);
imagedestroy($this->img);
}
//生成验证码内容
private function Get_code(){
$this->str=str_shuffle($this->str);
for($i=0;$i<4;$i++){
$this->code_content[$i]=substr($this->str,mt_rand($i,strlen($this->str)-1),1);
}
}
//生成干扰点
private function Get_pixle(){
for($i=0;$i<25;$i++){
imagesetpixel($this->img,mt_rand(0,$this->img_width),mt_rand(0,$this->img_height),imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}
}
//生成干扰线
private function Get_line(){
for($i=0;$i<4;$i++){
imageline($this->img,mt_rand(0,$this->img_width-1),mt_rand(0,$this->img_height-1),mt_rand(0,$this->img_width-1),mt_rand(0,$this->img_height-1),imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}
}
//session存储验证码
public function Session_code(){
session_start();
$_SESSION['code']=implode("",$this->code_content);
}
}
?>
- verify.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>登录/注册的验证码</title>
</head>
<body>
<form action="check_verify.php" method="post">
<input type="text" name="code" /><br/>
<img src="show_verify.php" onclick="this.setAttribute('src','show_verify.php?'+Math.random())" />
<span>点击图片刷新验证码</span><br/>
<input type="submit" name="sub" value="登录/注册" />
</form>
</body>
</html>
- show_verify.php
<?php
require './createverify.class.php';
$str='0123456789';
$font="./MONACO.TTF";
$code = new Createverify(100,40,$str,$font);
$code->Get_img();
?>
- check_verify.php
<?php
header('Content-type:text/html;charset="utf-8"');
session_start();
if($_POST['code']!=''){
if($_SESSION['code']==$_POST['code']){
echo '<script type="text/javascript">
alert("验证码正确");
window.location.href="verify.html";
</script>';
}else{
echo '<script type="text/javascript">
alert("验证码错误");
window.location.href="verify.html";
</script>';
}
}
?>
链接: https://pan.baidu.com/s/1dEXvcIX 密码: em38