php部分
function _code($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = false){
//会话功能// session_start();
//随机码的个数
//创建随机码,保存在session可以持久
for($i=0;$i<$_rnd_code;$i++){
@$_nmsg.= dechex(mt_rand(0, 15));//.是累计的意思累计4次,将十进制转换成十六进制将出现ABCDEF
}
$_SESSION['code'] =$_nmsg;
//创建一张图片
$_img = imagecreatetruecolor($_width, $_height);
//白色
$_white = imagecolorallocate($_img,255,255,255);
//填充
imagefill($_img,0,0,$_white);
//黑色
$_black = imagecolorallocate($_img,0,0,0);
//填充
//imagefill($_img,0,0,$_black);
//黑色边框
if($_flag){
imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);
}
//随机画出6个不同的线
for($i=1;$i<6;$i++){
$_rand_color = imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
$_image_line = imageline($_img,mt_rand(0,75),mt_rand(0,25),mt_rand(0,75),mt_rand(0,25), $_rand_color);
}
//随机雪花
for($i=0;$i<100;$i++){
$_mt_color = imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),'*',$_mt_color);
}
//输出验证码
for($i=0;$i<strlen($_SESSION['code']);$i++){
$_mt_color = imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));
imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1, 10),mt_rand(1,$_height/2),$_SESSION['code'][$i],$_mt_color);
}
//输出图片
header('Content-Type:image/png');
imagepng($_img);
//销毁
imagedestroy($_img);
}
调用函数
_code();
html部分
<dd>验 证 码:<input type="text" name="yzm" class="text yzm" /><img src="code.php" id="code" /></dd>
css部分
#register dl dd img#code{
position:relative;
top:7px;
cursor:pointer;
}
js部分
if(fm.yzm.value.length<4){
alert('验证码错误');
fm.yzm.value='';//清空用户名
fm.yzm.focus();//将光标焦点移至表单字段
return false;
}