php 验证码生成方法 及使用

时间:2023-03-09 02:17:49
php 验证码生成方法 及使用
基本思路是:
 在生成图片的页面中(as:
yzm.php)
1。设置生成的图片的宽度和高度;
2。设置图片要写入的字符;
3。截取显示在图片上的字符;
4.开启session,把上面截取的字符存放在session中,用session返回的值与填写的验证码是否相同;
5。用imagecreate()生成图片;
6。给上面生成的图片绘色,用imagecollorallocate(),第一次调用即为图片的底色;
7。再次用imagecollorallocate()定义要用到的颜色;
8。用imagestring()给生成的图片填充一些字符;
9。再用imagestring()给生成的图片写上上面截取的字符
10。用imagerectangle()给生成的图片画一个矩形
11。用header()指定输出的内容格式;
12。用imagepng等函数输出上面的图片;
13。用imageDestroy()
等函数销毁生成的图片

在调用上面生成的图片的表单用调用方法:
1。在表单用设置<img style="cursor:pointer"
title="xxx" id="refresh" src="yzm.php"
onclick="document.getElementById('refresh').src='yzm.php?t='+Math.random()"
/>
其中,里面的属性具体为:
style:设置鼠标放上去显示的鼠标状态;
title:鼠标在上面时显示的提示语;
id:用于JS脚本以便宜方便刷新;
src:包含的就是一幅图片,此时包含的是验证码的处理面,里面已经生成了图片了(相当于就是一幅图片);

提交时先用js在当前页面验证是否验证码框为空,再在提交页面处理填写的验证码字符是不是与session中相同即可通过了验证

yzm.php

<?php

//如果浏览器显示“图像XXX因其本身有错无法显示”,可尽量去掉文中空格
//先成生背景,再把生成的验证码放上去
$img_height=70;//先定义图片的长、宽
$img_width=25;
$authnum='';
//生产验证码字符
$ychar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
$list=explode(",",$ychar);
for($i=0;$i<4;$i++){
   
$randnum=rand(0,35);
   
$authnum.=$list[$randnum];
}
//把验证码字符保存到session
session_start();
$_SESSION["login_check_number"]
= $authnum;

$aimg = imagecreate($img_height,$img_width);   
//生成图片
imagecolorallocate($aimg, 255,255,255);           
//图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了
$black = imagecolorallocate($aimg,
0,0,0);        //定义需要的黑色

for ($i=1; $i<=100; $i++) {
   
imagestring($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"@",imagecolorallocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));
}

//为了区别于背景,这里的颜色不超过200,上面的不小于200
for
($i=0;$i<strlen($authnum);$i++){
    imagestring($aimg,
mt_rand(5,6),$i*$img_height/4+mt_rand(2,3),mt_rand(1,$img_width/2-2),
$authnum[$i],imagecolorallocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));
}
imagerectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//画一个矩形
Header("Content-type:
image/PNG");
ImagePNG($aimg);                   
//生成png格式
ImageDestroy($aimg);
?>

填写页面

<?php
session_start();
?>
<!DOCTYPE
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>111111</title>
<script>
function
check(form){
 if(form.verify.value == ""){
  alert("Not all empty!");
 
form.verify.select();
  return
false;
 }

}
</script>
</head>

<body>

<form
method='post' action='2.php' onSubmit="return check(this)">
<input
type='text' name='verify'>
<img style="cursor:pointer" title="刷新验证码"
id="refresh" border='0'
src='yzm.php'
onclick="document.getElementById('refresh').src='yzm.php?t='+Math.random()"/>
<button
type='submit'>确定</button>
</form>
<div
id="yzm">

</div>
</body>
</html>

处理表单页面
2.php
<?php
session_start();
if(strtolower($_SESSION['login_check_number'])
!= strtolower($_POST['verify'])){
  
 ///
}else{

}

?>