在网页中为了防止恶意的暴力破解登录,都会采用验证码的方式对非人为的方式进行初级的控制,下面就详细讲解一下如何在php登录页面中生成验证码:
1. 在login.js文件中生成随机数,生成的随机数作为参数传达到实际显示的验证码的那一页
代码如下:
showval(); // 调用showval()函数生成图文验证码
$('changea').onclick = showval; // 更换验证码 $('id') 是自己定义的一个函数 function $('id') { return document.getElementById('id');}
function showval(){
num= '' ;
for(i=0 ; i<4; i++){
tmp = Math.ceil(Math.random()*15); // 用来生成[0,15)之间的整数
if(tmp>9){
switch(tmp){
case(10):
num+='a';
break;
case(11):
num+='b';
break;
case(12):num+='c';
break;
case(13):num+='d';
break;
case(14):num+='e';
break;
case(15):
num+='f';
break;
}else{
num+=tmp;
}
}
$('chkid').src="valcode.php?num="+num;
$('chknum').value=num; // 这是在登录页中的隐藏域,用来保存这次生成的验证码,以便于和用户输入的验证码相比较。
}
2. valcode.php 实现验证码的验证和刷新,验证码页面采用gd2技术:
header("content-type:image/png");
$num=$_GET['num']; // 接收在js页面中传过来的随机数的值
$imagewidth = 60 ;
$imageheight =18; // 这是定义画布的长和宽
$numimage = imagecreate($imagewidth,$imageheight); // 创建画布
imagecolorallocate($numimage,$imagewidth,$imageheght); // 创建一个图像
for ($i=0;$i
$x = mt_rand(1,8)+$imagewidth*$i/4; // 获取文字左上角X做坐标
$y = my_rand(1,$imageheight/4); // 获取文字左上角的y坐标
$color = imagecolorallocate($numimage,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150)); // 为文字分配颜色
imagestring($numimage,5,$x,$y,$num[$i],$color); // 写入文字
}
// 接下来是生成干扰码
for($i=0 ; $i<200 ; $i++){
$randcolor = imagecolorallocte($numimage,rand(0,255),rand(0,255),rand(0,255)); // 生成随机的颜色
imagesetpixel($numimage,random()%70,random()%20,$randcolor);
}
$imagepng($numimage); // 输出png格式的图片
$imagedestroy($numimage); // 销毁图片
?>
到此设计验证码的基本技术已经讲完了,望大家借鉴参考。