PHP图片中文验证码

生成验证码图片文件:

<?php 
 session_start();
/*
1.创建随机数  2.创建图片  3.随机数写进图片(随机中文写进图片)  验证:通过将$a保存在session中
*/
 for ($i=0; $i < 4; $i++) {
    $a.=dechex(rand(1,15)); 
 	# code...
 }

$_SESSION[check]=$a;//随机数保存到session
$img=imagecreatetruecolor(90,30);//新建一个真彩色图像
$white=imagecolorallocate($img,255, 255, 255);//为一幅图像分配颜色
$arr= array(
行尸走肉,百里挑一,金蝉脱壳,攻城掠地,春暖花开,
国色天香,天上人间,怦然心动,书香门第,海阔天空,
金玉良缘,千方百计,情不自禁,霸王别姬,满腹经纶,
);
$arrkey=array_rand($arr,1);//默认是1 在数组里随机取一个或多个键(下标)。
$arrvalue=$arr[$arrkey];//根据键获得对应的值
$_SESSION[check1]=$arrvalue;
//用imageline()函数画线条
for ($i=0; $i <4; $i++) {
 $linecolor=imagecolorallocate($img,rand(0,255), rand(0,255),rand(0,255));
 imageline($img,rand(0,30), rand(0,30), rand(30,100),rand(15,30), $linecolor);
	# code...
}
//用imagesetpixel()函数画噪点
for ($i=0; $i <150 ; $i++) {
 imagesetpixel($img, rand()%100, rand()%30,$white); 
	# code...
}
//中文验证码imagettftext()向图片写入指定字体文本
imagettftext($img,12, 0, 20, 20,$white, 'msyh.ttc', $arrvalue);

//把字符串写在图像左上角
//imagestring($img, 5, rand(20,50), rand(5,15), $a, $white);//绘图函数将随机数通过……写入$img.
header("content-type:image/jpeg");
imagejpeg($img);
?>

  

验证文件:

<?php
 session_start();
 if ($_POST[sub]) {
 	if ($_POST[check]==$_SESSION[check1]) {
 		echo "通过验证";
 		# code...
 	}else{
 		echo "验证失败";
 	}
 	# code...
 }

?>
<meta http-equiv="content-type" content="text/html;charset=utf8">
 <form action="" method="post">
    <img src="tupian.php">
 	<input type="text" name="check">
 	<input type="submit" name="sub" value="check">
 </form>

  

posted @ 2014-04-13 23:41  选择了就坚持  阅读(238)  评论(0编辑  收藏  举报