Rumah >pembangunan bahagian belakang >tutorial php >php中文字母数字验证码实现代码_php技巧
英文同数字
Header("Content-type:image/png");
//定义header,声明图片文件,最好是png,无版权之扰;
//生成新的四位整数验证码
session_start();//开启session;
$authnum_session = '';
$str = 'abcdefghijkmnpqrstuvwxyz1234567890';
//定义用来显示在图片上的数字和字母;
$l = strlen($str); //得到字串的长度;
//循环随机抽取四位前面定义的字母和数字;
for($i=1;$i{
$num=rand(0,$l-1);
//每次随机抽取一位数字;从第一个字到该字串最大长度,
//减1是因为截取字符是从0开始起算;这样34字符任意都有可能排在其中;
$authnum_session.= $str[$num];
//将通过数字得来的字符连起来一共是四位;
}
session_register("authnum_session");
//用session来做验证也不错;注册session,名称为authnum_session,
//其它页面只要包含了该图片
//即可以通过$_SESSION["authnum_session"]来调用
//生成验证码图片,
srand((double)microtime()*1000000);
$im = imagecreate(50,20);//图片宽与高;
//主要用到黑白灰三种色;
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
$gray = ImageColorAllocate($im, 200,200,200);
//将四位整数验证码绘入图片
imagefill($im,68,30,$gray);
//如不用干扰线,注释就行了;
$li = ImageColorAllocate($im, 220,220,220);
for($i=0;$i{//加入3条干扰线;也可以不要;视情况而定,因为可能影响用户输入;
imageline($im,rand(0,30),rand(0,21),rand(20,40),rand(0,21),$li);
}
//字符在图片的位置;
imagestring($im, 5, 8, 2, $authnum_session, $white);
for($i=0;$i{//加入干扰象素
imagesetpixel($im, rand()%70 , rand()%30 , $gray);
}
ImagePNG($im);
ImageDestroy($im);
?>
中文
/*
* 文件:code.php
* 作用:验证码生成
*/
session_start();
// 设置 content-type
header("Content-type: image/png");
// 创建图片
$im = imagecreatetruecolor(120, 30);
$ChineseChar = array("人","出","来","友","学","孝","仁","义","礼","廉","忠","国","中","易","白","者","火 ","土","金","木","雷","风","龙","虎","天","地",
"生","晕","菜","鸟","田","三","百","钱","福 ","爱","情","兽","虫","鱼","九","网","新","度","哎","唉","啊","哦","仪","老","少","日",
"月 ","星");
// 创建颜色
$fontcolor = imagecolorallocate($im, 255, 255, 255);
$bg = imagecolorallocate($im, 0, 0, 0);
// 设置文字
for($i=0;$i
$_SESSION['code'] = $text;
// 设置字体 [url]http://www.font.com.cn/downlist/s_12_3.html[/url] 有_GBK系列的字体下载,一般GD库都支持的!
$font = 'gbk.ttf';
// 添加文字
imagettftext($im, 18, 0, 11, 21, $fontcolor, $font, iconv("GB2312","UTF-8",$text));
// 输出图片
imagepng($im);
imagedestroy($im);
?>