PHP中使用PD库实现动态验证码生成
本帖最后由 Sian 于 2016-1-6 12:08 编辑index.php<?php
session_start();
$code = $_SESSION["code"];
if (isset($_POST["dosubmit"])){
if($_POST["code"] == $code){
echo "验证成功!";
}else{
echo "验证码不正确!";
}
}
?>
<body>
<form action="" method="POST">
用户名:<input type="text" name="username" value=""/><br/>
密码:<input type="password" name="password" value="" /><br/>
验证码:<input type="text" size="4" name="code" />
<img src="code.php" on click = "this.src='code.php?+Math.random()'"/><br/>
<input type="submit" name="dosubmit" value="登录" /><br/>
</form>
</body>
code.php<?php
// 开启session
session_start();
include 'vcode.class.php';
$vcode = new Vcode(80, 25, 4);
// 将验证码放到服务器自己的空间保存一份
$_SESSION["code"] = $vcode->get_code();
// 将验证码的图片输出
$vcode->out_img();vcode.class.php<?php
class Vcode{
// 定义变量
private $width, $height, $number, $code, $image;
// 构造函数
function __construct($width, $height, $number){
$this->width = $width;
$this->height = $height;
$this->number = $number;
$this->code = $this->create_code();
$this->image = imagecreate($this->width, $this->height);
}
// 输出图片
function out_img(){
// 创建颜色
$white = imagecolorallocate($this->image, 255, 255, 255);
$blank = imagecolorallocate($this->image, 0, 0, 0);
// 渲染背景、边框
imagefill($this->image, 0, 0, $white);
imagerectangle($this->image, 0, 0, $this->width-1, $this->height-1, $blank);
// 画图
$w = imagefontwidth(5); // 字体宽度
$h = imagefontheight(5); // 字体高度
$width = $this->width / $this->number; // 单字宽度
for ($i = 0; $i < $this->number; $i++){
// 每一个字符在各自四分之一个格子内随机
$x = rand($width * $i, $width + $width * $i - $w);
$y = rand(0, $this->height - $h);
// 颜色随机
$color = imagecolorallocate($this->image, rand(0, 200), rand(0, 200), rand(0, 200));
// 渲染字符
imagestring($this->image, 5, $x, $y, $this->code[$i], $color);
}
// 干扰元素点
for($i = 0; $i < 100; $i ++){
// 颜色随机
$color = imagecolorallocate($this->image, rand(0, 200), rand(0, 200), rand(0, 200));
// 位置在图像范围内
$x = rand(1, $this->width-2);
$y = rand(1, $this->height-2);
// 画一个像素点
imagesetpixel($this->image, $x, $y, $color);
// 增加10条干扰线条
if($i % 10 == 0){
// 椭圆长半径及短半径随机
$width = rand(20, 300);
$height = rand(20, 300);
// 随机画孤
imagearc($this->image, $x, $y, $width, $height, 55, 44, $color);
}
}
// 输出图像
return imagegif($this->image);
}
// 获取字符的验证码
function get_code(){
return $this->code;
}
// 生成验证码字符串
private function create_code(){
return "".rand(1000, pow(10, $this->number) - 1);
}
// 析构函数
function __destruct(){
imagedestroy($this->image);
}
}
页:
[1]