验证码生成代码(authCode.php):
<?php
Header("content-type: image/png");
//获取随机颜色
function getRandomColor($img)
{
return ImageColorAllocate($img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
}
//生成验证码
function createAuthCode($length)
{
$code_en=str_split("abcdefghjkmnopqrstuvwxy34567890ABCDEFGHJKMNOPQRSTUVWXY");
$code_zh=Array('君','不','见','黄','河','之','水','天','上','来','奔','流','到', '海','不','复','回','人','生',
'得','意','须','尽','欢','孤','帆','远','影','碧','空','尽','天','生','我','材','必','有','用','华');
$randCode=Array($code_en,$code_zh);
//在fonts目录下存放字体文件
$fontFace_en="fonts/GEORGIA.TTF"; //用于英文
$fontFace_zh="fonts/STXINGKA.TTF"; //用于中文
$randFontFace=Array($fontFace_en,$fontFace_zh);
$image_x=25*$length; //图片宽度
$image_y=30; //图片高度
$noise_num=25*$length; //噪点数量
$arc_num=$length/2 + 1; //干扰弧线数量
//建立新图,设定背景色
$image=ImageCreate($image_x,$image_y);
ImageColorAllocate($image,255,255,255);
//加边框
$rectangle_color=ImageColorAllocate($image,221,221,221);
ImageRectangle($image,0,0,$image_x-1,$image_y-1,$rectangle_color);
//加入噪点
for($i=0;$i < $noise_num;$i++)
{
ImageSetPixel($image,mt_rand(0,$image_x),mt_rand(0,$image_y),getRandomColor($image));
}
//加入干扰弧线
for($i=0; $i < $arc_num; $i++)
{
ImageArc($image, mt_rand(0,$image_x), mt_rand(0,$image_y), mt_rand(60,300), mt_rand(20,100), 50, 35, getRandomColor($image));
}
//加入验证码字符
$x=6;
$session_code='';
$randomIndex=mt_rand(0,1);
$code=$randCode[$randomIndex];
$maxIndex=count($code)-1;
$fontFace=$randFontFace[$randomIndex];
for($i=0;$i < $length;$i++)
{
$char=$code[mt_rand(0,$maxIndex)];
ImageTTFText($image,16,mt_rand(-30,30),$x,23,getRandomColor($image),$fontFace,$char);
$session_code .= $char;
$x+=23;
}
//存入session中
@session_start();
$_SESSION['authCode']=$session_code;
ImagePng($image);
ImageDestroy($image);
}
createAuthCode(5-1);
?>
验证码查看页面(viewCode.php):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>查看验证码</title>
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<img src="authCode.php" onclick="this.src='authCode.php?id='+Math.random();" />
</body>
</html>
效果图: