码迷,mamicode.com
首页 > Web开发 > 详细

PHP制作验证码

时间:2016-05-12 15:45:35      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

学习目的:
屏蔽机器请求,保证业务不受机器提交请求干扰。
为什么要屏蔽:
一般服务端业务,写请求产生的消耗要远远大于读请求
技术点:
1.底图的实现,并且添加干扰元素
2.生成验证内容
3.验证内容保存在服务端
4.验证内容的效验
技术分享

实现底图:
技术分享
代码:

<?php
$img = imagecreatetruecolor(100,30);//大小
$bgColor = imagecolorallocate($img,0x00,0x00,0x00);//背景颜色
imagefill($img,0,0,$bgColor);//填充颜色
header(‘content-type: image/png‘);
imagepng($img);
//销毁
imagedestroy($img);

增加点干扰和线干扰:

<?php
$img = imagecreatetruecolor(100,30);//大小
$bgColor = imagecolorallocate($img,0xff,0xff,0xff);//背景颜色
imagefill($img,0,0,$bgColor);//填充颜色
//增加随机数字
for($i=0;$i<4;$i++){
    $numberSize = 6;
    $numberColor = imagecolorallocate($img,rand(0,120),rand(0,120),rand(0,120));//深色区间
    //位置不能重合
    $x = ($i*100/4)+rand(0,5);
    $y = rand(5,10);
    imagestring($img,$numberSize,$x,$y,rand(0,9),$numberColor);
}
//增加点干扰
for ($i=0;$i<200;$i++){
    //干扰颜色
    $pointColor = imagecolorallocate($img,rand(50,200),rand(50,200),rand(50,200));
    imagesetpixel($img,rand(0,100),rand(0,30),$pointColor);
}
//增加线干扰
for ($i=0;$i<4;$i++){
    //干扰颜色
    $lineColor = imagecolorallocate($img,rand(80,200),rand(80,200),rand(80,200));
    imageline($img,rand(0,100),rand(0,30),rand(0,100),rand(0,30),$lineColor);
}
header(‘content-type: image/png‘);
imagepng($img);
//销毁
imagedestroy($img);

注意事项:
干扰信息一定要控制好颜色,不要“喧宾夺主”。

通过SESSION存储验证信息

目标:
在服务端记录验证码信息,便于用户输入后做效验
方法:
session_start()
注意事项:
1.session_start**必须处于脚本最顶部**
2.多服务器情况,需要考虑集中管理session信息

自己解决乱码问题:转换为UTF-8无BOM格式编码。

技术分享

图片和视频验证原理是一样的,只是维护了一个图片物料库和其对应session的关系而已。

中文验证码的实现
实现:
依赖GD库的imagettftext()方法
注意:
1.GBK编码时,需要将中文通过iconv()转为UTF-8
2.选用的TTF文件需要支持中文

在utf-8中,中文字体占3个字节?(不确定)。

PHP制作验证码

标签:

原文地址:http://blog.csdn.net/he_world/article/details/51365655

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