验证码的实现

本文介绍了一种使用PHP生成带有随机字符、线条、雪花及噪点的验证码的方法,并提供了完整的PHP代码实现。此外,还详细介绍了如何通过session进行验证码的验证。

一、核心代码

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

 

四、测试

 

转载于:https://www.cnblogs.com/zzmgg/p/6143180.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值