php生成验证码函数

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

 php生成验证码函数

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

  1. <?php 
  2. session_start(); 
  3. //session_register('CheckCode');  
  4. //PHP4.2以上版本不需要用session_register()注册SESSION变量 
  5. $type='gif'
  6. $width= 45; 
  7. $height= 20; 
  8. header("Content-type: image/".$type); 
  9. srand((double)microtime()*1000000); 
  10. if(isset($_GET['action'])){ 
  11.     $randval=randStr(4,$_GET['action']);     
  12. }else
  13.     $randval=randStr(4,'');  
  14. if($type!='gif'&&function_exists('imagecreatetruecolor')){ 
  15.     $im=@imagecreatetruecolor($width,$height); 
  16. }else
  17.     $im=@imagecreate($width,$height); 
  18. $r=Array(225,211,255,223); 
  19. $g=Array(225,236,237,215); 
  20. $b=Array(225,236,166,125); 
  21. $key=rand(0,3); 
  22. $backColor=ImageColorAllocate($im,$r[$key],$g[$key],$b[$key]);//背景色(随机) 
  23. $borderColor=ImageColorAllocate($im,127,157,185);//边框色 
  24. $pointColor=ImageColorAllocate($im,255,170,255);//点颜色 
  25. @imagefilledrectangle($im,0,0,$width - 1,$height - 1,$backColor);//背景位置 
  26. @imagerectangle($im,0,0,$width-1,$height-1,$borderColor); //边框位置 
  27. $stringColor=ImageColorAllocate($im,255,51,153); 
  28. for($i=0;$i<=100;$i++){ 
  29.     $pointX=rand(2,$width-2); 
  30.     $pointY=rand(2,$height-2); 
  31.     @imagesetpixel($im,$pointX,$pointY,$pointColor); 
  32. @imagestring($im,5,5,1,$randval,$stringColor); 
  33. $ImageFun='Image'.$type
  34. $ImageFun($im); 
  35. @imagedestroy($im); 
  36. $_SESSION['CheckCode']=$randval
  37. function randStr($len=6,$format='ALL'){ 
  38.     switch($format){ 
  39.         case 'ALL'://生成包含数字和字母的验证码 
  40.             $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'break
  41.         case 'CHAR'://仅生成包含字母的验证码 
  42.             $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'break
  43.         case 'NUMBER'://仅生成包含数字的验证码 
  44.             $chars='0123456789'break
  45.         default : 
  46.             $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'break
  47.     } 
  48.     $string=''
  49.     while(strlen($string)<$len
  50.     $string.=substr($chars,(mt_rand()%strlen($chars)),1); 
  51.     return $string

该函数的具体使用方法请看如下这个示例(这里是生成全数字的验证码): 更多PHP教程,请访问代码家园

  1. <img src="checkCode.php?action=NUMBER" width="45" height="20" /> 

 


本文原地址:http://www.daimajiayuan.com/sitejs-16919-1.html

posted @ 2014-04-23 14:28  似水星辰  阅读(598)  评论(0编辑  收藏  举报