php 基于GD库验证码

页面关键html代码

 

  <div align="center">
     请输入验证码<input type="text" name="yanzheng" id="yanzheng"  size="3" onBlur="checkcode()"/> <a onClick="document.getElementById('yanimage').src='yan.php?'+Math.random()"><input type=image src="yan.php" align="absmiddle"  id="yanimage"  >看不清 </a>
       </div>


checkcode()方法,采用ajax校验验证码

 

<script>
var flag="true";
var xmlHttp;
function checkcode(){
var yanzheng=document.getElementById("yanzheng").value; 
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("浏览器不支持")
 return
 }
var url="check.php";
url=url+"?y="+yanzheng;
url=url+"&sid="+Math.random();

xmlHttp.onreadystatechange=stateChanged0;
xmlHttp.open("GET",url,true);
xmlHttp.send();
}
function stateChanged0() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
   var yanzheng=xmlHttp.responseText;
   if (yanzheng==1){
   alert("验证码错误!");
   flag="false";
 //  document.signupForm.yanzheng.select();
   }
 } 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}
</script>

 

调用GD库类,画验证码


 

<? 

 //随机生成一个4位数字的验证码  
 $num=''; 
 for($i=0;$i<4;$i++){ 
     $num.=dechex(rand(0,20));  //dechex函数是十进制转会二进制  
 } 
 session_start();   //开启session  
 $_SESSION['yan']=substr($num,0,4);  //用session记住这个验证数字  
 header("Content-type:image/PNG"); 
 $im=imagecreate(60,20);  //创建一个画布  
 $back=imagecolorallocate($im,rand(0,55),rand(0,20),rand(0,5));//创建一个背景颜色 (黑色)  
 $gray=imagecolorallocate($im,rand(0,255),rand(0,200),rand(0,55)); //(白色)  
 imagefill($im,0,0,$gray);   //填充颜色  
 $style=array($back,$back,$back,$back,$back,$gray,$gray,$gray,$gray,$gray); //生成数组  
 imagesetstyle($im,$style);    //设定画线风格  
 $y1=rand(0,20); 
 $y2=rand(0,20); 
 $y3=rand(0,20); 
 $y4=rand(0,20); 
 imageline($im,0,$y1,60,$y3,IMG_COLOR_STYLED);     //画一条线  
 imageline($im,0,$y2,60,$y4,IMG_COLOR_STYLED); 
 //在画布上随机生成大量黑点,起干扰作用  
 for ($i=0;$i<80;$i++){ 
     imagesetpixel($im,rand(0,60),rand(0,20),$back); 
 } 
 $str=rand(3,8); 
 for ($i=0;$i<4;$i++){ 
     $strp=rand(1,6); 
     imagestring($im,6,$str,$strp,substr($num,$i,1),$back); 
     $str+=rand(8,12); 
 } 
 ImagePNG($im); 
 imagedestroy($im); 
 ?> 


判断输入和生成是否相同代码,注意前面开启session

session_start();
//验证验证码
 if ($_GET['y']){	
 $y=$_GET["y"];
 if ($y!=$_SESSION['yan']){echo "1";}
 }


 

你可能感兴趣的:(PHP,session,function,XMLhttpREquest,Safari,IM)