码迷,mamicode.com
首页 > 其他好文 > 详细

验证码的实现

时间:2016-12-08 02:48:53      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:cat   range   url   include   点击   img   判断   set   refresh   

一、核心代码

<?php
// 1, 加载项目初始化文件
include ‘../init.php‘;

//创建画布
$img = imagecreatetruecolor(200,40);

//创建画笔
$color = imagecolorallocate($img,mt_rand(100,255),mt_rand(150,255),mt_rand(160,225));
//填充区域
imagefill($img,0,0,$color);

//制作随机验证码
$arr = array_merge(range(‘A‘,‘Z‘),range(‘a‘,‘z‘),range(0,9));
//打乱数组
shuffle($arr);
$rand_keys = array_rand($arr,4);//随机获得该数组4个值的下标
//依次根据数组的键获得数组的值,拼凑到一起 ;
$str = ‘‘;
foreach($rand_keys as $value){
$str .= $arr[$value];
}
//保存到session中
session_start();
$_SESSION[‘code‘] = $str;
//echo $str;die;
//将验证码数据写到图片上面
//计算字符间隔
$span = ceil(200/(4+1));

for($i=1;$i<=4;$i++){
$numcolor = imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
imagestring($img,5,$i*$span,10,$str[$i-1],$numcolor);
}
//创建模糊线段
for($i=1;$i<=6;$i++){
$linecolor = imagecolorallocate($img,mt_rand(0,30),mt_rand(0,50),mt_rand(0,80));
imageline($img,mt_rand(0,199),mt_rand(0,40),mt_rand(0,199),mt_rand(0,40),$linecolor);
}
//创建雪花模糊
for($i=1;$i<=10;$i++){
$xuecolor = imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
imagestring($img,3,mt_rand(0,199),mt_rand(0,40),‘*‘,$xuecolor);
}
//创建干扰点(噪点)
for($i=1;$i<=200*40*0.03;$i++){
$pixcolor = imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
imagesetpixel($img,mt_rand(0,199),mt_rand(0,39),$pixcolor);
}
//清理数据缓冲区
ob_clean();
//输出图片
header(‘content-type:image/png‘);

imagepng($img);

 

二、点击刷新验证码

技术分享

三、验证

//首先验证验证码
session_start();
$code = $_SESSION[‘code‘];
//判断
if(strtolower($vcode) !== strtolower($code)){
header("refresh:2;url=./register.php");
die("验证码不正确!");
}

 

四、测试

技术分享

 

验证码的实现

标签:cat   range   url   include   点击   img   判断   set   refresh   

原文地址:http://www.cnblogs.com/zzmgg/p/6143180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!