代码改变世界

验证码的实现

2016-12-07 23:01  钟帜铭哥哥  阅读(232)  评论(0编辑  收藏  举报

一、核心代码

<?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("验证码不正确!");
}

 

四、测试