验证码处理技术

来源:互联网 发布:补水爽肤水推荐知乎 编辑:程序博客网 时间:2024/06/04 19:46

分析:
码值:大写字母&数字随机选择,位置居中,黑白随机
背景:固定的背景图片见随机。
支持点击更换

CAPTCHA项目是Completely Automated Public Turing Test to Tell Computers and Humans Apart (全自动区分计算机和人类的图灵测试)的简称


示例代码:

<?php
//生成码值
$chars='ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';  //所有可能的字符
$char_len=strlen($chars);
$code_len=6;   //设置码值的长度
$code=' '; //初始化码值字符串
for($i=1;$i<=$code_len;++$i){
 $rand_index=mt_rand(0,$char_len-1);  //下标从开始
 $code .= $chars[$rand_index];  //字符串支持[]操作,通过下标获取某个字符
}
//存储于session,用于验证
session_start();
$_SESSION['captcha_code']=$code;
//背景图
$bg_file='./picture/captcha_bg' . mt_rand(1,5) . '.jpg';

//基于jpg格式的图片创建画布
$img=imageCreateFromJPEG($bg_file);

//操作画布,分配文字的颜色,用函数 imageColorAllocate();
$str_color=mt_rand(1,3)==1?imageColorAllocate($img,0,0,0):imageColorAllocate($img,0xff,0xff,0xff);

//将字符串写到图片上,imageString(画布,字体,位置X,位置Y,字符串内容,颜色)
//字体:该函数使用的内置字体,1-5表示。差异1小5大
//位置X,Y:左边字符的左上角的位置来确定。
$font=5;
//计算字符串的居中:
//画布大小:imageSX(画布)宽, imageSY(画布)高
//内置字体大小:imageFontWidth(字体号)宽,imageFontHeight(字体号)高;
//画布尺寸
$img_w=imageSX($img);
$img_h=imageSY($img);
//字体的尺寸
$font_w=imagefontwidth($font);
$font_h=imagefontheight($font);
//字符串的尺寸
$code_w=$font_w*$code_len;
$code_h=$font_h;
$x=($img_w-$code_w)/2;
$y=($img_h-$code_h)/2;
imageString($img,$font,$x,$y,$code,$str_color);

//输出,销毁画布
header('Content-Type: image/jpeg;');
imageJPEG($img);

imageDestroy($img);

0 0