这篇文章给大家介绍的内容是关于php实现验证码的步骤以及服务端校验的代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
验证码是什么:验证码是一种区分用户是计算机还是人的公共程序
制作验证码需要四步
1:生成底图
2:生成验证内容
3:生成验证码内容
4:校验验证内容
先分步,第一步,生成底图:
目标:通过php生成一张100*30大小的图片
方法:imagecreatetruecolor($width,$height);
注意事项:依赖GD扩展
在输出图片前,必须提前输出那张图片的header 信息 –》》发送原生http头
该方法默认输出黑色背景
imagecreatetruecolor() 新建一个真彩色图像 用$image来表示,之后,会大量用到
既然是创建真彩图像,那就要有多样的颜色 ,下面imagecolorallocate(选画布,三色参数)
要用什么意思填充 imagefill(选画布,开始位置 ,颜色)
致此,生成了底图,下面开始加点作料
$image = imagecreatetruecolor(100,30)
$bgcolor = imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor)
第二步:生成验证内容
目标:随机生成数字(大小,开始位置,内容,颜色)
方法:通过循环,imagestring 函数 ,水平的生成一行字符串(根据imagestring里面参数位置,往进填)
注意事项:控制好字体大小,N/n
for($i=0;$<4;i++){
此处根据imagestring里面的参数,定义变量,并且为变量赋值
imagestring($image,$fontsze,$x,$y,$fontcontent,$fontcolor)
}
$fontcontent = substr($data,rand(0,strlen($data)),1);
如果要数字和字母的组合,substr方法的意思是返回字符串的子串,返回的字符串随机取得data,从这开始,最多有1个长度
第三步生成验证码 内容
目标:为验证码增加干扰元素,干扰元素为点或线
方法:imagesetpixel点,imageline-线(资源文件,起始位置,颜色)
注意事项:干扰元素一定要控制好颜色和数量,避免喧宾夺主
第四步:通过session存储验证信息
目标:在服务器端做记录,便于用户输入验证码后做校验
方法:session_start()
注意事项:session_start()必须处于脚本最顶端
多服务情况下,要考虑集中管理sessi8本文来源gao.dai.ma.com搞@代*码(网$
搞代gaodaima码
on管理
imagepng 以png格式将图片输出到浏览器或文件
imagedestroy 销毁图片 好习惯
在这些方法中,资源的使用非常多,就是每一个方法都要$image这个画布
<php?$image = imagecreatetruecolor( 100,30);$bgcolor = imagecolorallocate($image,255,255,255);imagefill($image,0,0,$bgcolor);// for($i=0;$i<4;$i++){// $fontsize = 6;// $fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));// $fontcontent = rand(0,9);// $x = ($i*100/4)+rand(5,10);// $y = rand(5,10);// imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor );// }$captch_code= '';for($i=0 ;$i<4;$i++){ $fontsize = 6; $fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120)); $data = 'abcdefhijkimnpqrstuvwxy345678'; $fontcontent = substr($data,rand(0,strlen($data)),1); $captch_code.=$fontcontent; $x = ($i*100/4)+rand(5,10); $y = rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor ); }$SESSION['authcode']=$captch_code;for($i=0;$i<200;$i++){$pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));imagesetpixel($image,rand(1,99),rand(1,99),$pointcolor);}for($i=0;$i<3;$i++){$linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));imageline($image,rand(1,99),rand(1,99),rand(1,99),rand(1,99),$pointcolor);}header('content-type: image/png');imagepng( $image);//end;imagedestroy( $iamge);?>