当前位置: 移动技术网 > IT编程>开发语言>PHP > php生成验证码函数

php生成验证码函数

2018年05月01日  | 移动技术网IT编程  | 我要评论

武林世家粤语,法克尤尔,快乐男声2011

php生成验证码的函数,实用靠谱。先上下生成的验证码的效果图(这里生成的是全数字的验证码的示例效果):

下面是php生成验证码的源码:

<?php 
session_start(); 
//session_register('checkcode'); 
//php4.2以上版本不需要用session_register()注册session变量 
$type='gif'; 
$width= 45; 
$height= 20; 
header("content-type: image/".$type); 
srand((double)microtime()*1000000); 
if(isset($_get['action'])){ 
 $randval=randstr(4,$_get['action']);  
}else{ 
 $randval=randstr(4,''); 
} 
if($type!='gif'&&function_exists('imagecreatetruecolor')){ 
 $im=@imagecreatetruecolor($width,$height); 
}else{ 
 $im=@imagecreate($width,$height); 
} 
$r=array(225,211,255,223); 
$g=array(225,236,237,215); 
$b=array(225,236,166,125); 
$key=rand(0,3); 
$backcolor=imagecolorallocate($im,$r[$key],$g[$key],$b[$key]);//背景色(随机) 
$bordercolor=imagecolorallocate($im,127,157,185);//边框色 
$pointcolor=imagecolorallocate($im,255,170,255);//点颜色 
@imagefilledrectangle($im,0,0,$width - 1,$height - 1,$backcolor);//背景位置 
@imagerectangle($im,0,0,$width-1,$height-1,$bordercolor); //边框位置 
$stringcolor=imagecolorallocate($im,255,51,153); 
for($i=0;$i<=100;$i++){ 
 $pointx=rand(2,$width-2); 
 $pointy=rand(2,$height-2); 
 @imagesetpixel($im,$pointx,$pointy,$pointcolor); 
} 
@imagestring($im,5,5,1,$randval,$stringcolor); 
$imagefun='image'.$type; 
$imagefun($im); 
@imagedestroy($im); 
$_session['checkcode']=$randval; 
function randstr($len=6,$format='all'){ 
 switch($format){ 
  case 'all'://生成包含数字和字母的验证码 
   $chars='abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789'; break; 
  case 'char'://仅生成包含字母的验证码 
   $chars='abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; break; 
  case 'number'://仅生成包含数字的验证码 
   $chars='0123456789'; break; 
  default : 
   $chars='abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789'; break; 
 } 
 $string=''; 
 while(strlen($string)<$len) 
 $string.=substr($chars,(mt_rand()%strlen($chars)),1); 
 return $string; 
}

 该函数的具体使用方法请看如下这个示例(这里是生成全数字的验证码):

<img src="checkcode.php?action=number" width="45" height="20" /> 

以上就是php如何生成验证码的实现函数,希望对大家的学习有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网