首页 > 开发 > PHP > 正文

php网页生成验证码实现程序

2024-05-04 21:58:15
字体:大 中 小
来源:转载
供稿:网友

首先在表单页面展现之前,生成一副图片,并添加上一些干扰像素或线段,防止OCR程序自动识别,再由PHP程序自动生成随机的待验证的一串数字和字母组合的字符,调用imagettftext()函数画到图片中,并把这串字符保存到Session级变量中.

完整实例:自动检测背景和字体,并随机选取背景图片中的一块范围,随机使用字体,显示验证字符串时随机显示字体大小,字符间距,字符颜色等,代码如下:

  1. <?php 
  2. /** 
  3. * Class for Validate image 
  4. * @author  zcs 
  5. * @version 1.0-20090828 
  6. */ 
  7.  
  8. session_start(); 
  9. class validimg 
  10. { 
  11. //背景图片目录 
  12. var $backgroundpath = ‘validbg’; 
  13. //生成验证码宽度 
  14. var $width =’80′; 
  15. //生成验证码高度 
  16. var $height =’25′; 
  17. //背景 
  18. var $background; 
  19. //验证文本 
  20. var $text=’abcd’; 
  21. //字体目录 
  22. var $fontpath = ‘validbg’; 
  23. //字体 
  24. var $font=’simhei.ttf’; 
  25. //字体宽度 
  26. var $font_width = ’20′; 
  27.  
  28. function validimg($text) 
  29. { 
  30. $this->text = $text; 
  31. //随机选取一个背景文件 
  32. $bgdir =  @dir($this->backgroundpath); 
  33. while(false !== ($image = $bgdir ->read())) 
  34. { 
  35. if($image != ‘.’ && $image != ‘..’ && $this->checktype($image) != false) 
  36. { 
  37. $backgroundarr[] = $image; 
  38.  
  39. } 
  40. } 
  41. $bgdir->close(); 
  42. //随机选取一个字体文件 
  43. $fonts =  @dir($this->fontpath); 
  44. while(false !== ($font = $fonts ->read())) 
  45. { 
  46. if($font != ‘.’ && $font != ‘..’ && $this->checktype($font,’FONT’) != false) 
  47. { 
  48. $fontsarr[] = $font; 
  49. } 
  50. } 
  51. $fonts->close(); 
  52. $this->font = $fontsarr[array_rand($fontsarr,1)]; 
  53. $this->background = $backgroundarr[array_rand($backgroundarr,1)]; 
  54.  
  55. $this->output(); 
  56. } 
  57.  
  58. //创建背景图像handdle 
  59. function createbackground() 
  60. { 
  61. switch ($this->checktype($this->background)) 
  62. { 
  63. case ‘jpg’: 
  64. $bghanddle = @imagecreatefromjpeg( $this->backgroundpath.’/’.$this->background); 
  65. break; 
  66. case ‘gif’: 
  67. $bghanddle = @imagecreatefromgif( $this->backgroundpath.’/’.$this->background); 
  68. break; 
  69. case ‘png’: 
  70. $bghanddle = @imagecreatefrompng( $this->backgroundpath.’/’.$this->background); 
  71. break; 
  72. default: 
  73. } 
  74. return $bghanddle; 
  75. } 
  76. //检查文件类型 
  77. function checktype( $image,$type = ‘IMAGE’) 
  78. { 
  79. $ext = substr( $image, strrpos($image,’.')+1); 
  80. if($type == ‘IMAGE’) 
  81. { 
  82. if ($ext == ‘jpg’ || $ext ==’gif’ || $ext ==’png’) 
  83. return $ext; 
  84. else return false; 
  85. }else if($type == ‘FONT’) 
  86. { 
  87. if ($ext == ‘ttf’) 
  88. return $ext; 
  89. else return false; 
  90. } 
  91. } 
  92. //输出 
  93. function output() 
  94. { 
  95. header(“content-type:image/png;”); 
  96. //生成图像 
  97. $img = @imagecreatetruecolor( $this->width,$this->height); 
  98. $bghanddle = $this->createbackground(); 
  99. //从背景图像随机位置载入一块作为背景 
  100. if($bghanddle) 
  101. { 
  102. $randx=rand(0,(imagesx($bghanddle) – $this->width)); 
  103. $randy=rand(0,(imagesy($bghanddle) – $this->height)); 
  104. } 
  105. imagecopy($img,$bghanddle,0,0,$randx,$randy,$this->width,$this->height); 
  106. //随机选择角度 字体大小 坐标输出文字 
  107. for($i=0;$i<strlen($this->text);$i++) 
  108. { 
  109. $angle = rand(-30,30); 
  110. $fontsize = rand(15,20); 
  111. $x = rand($this->font_width*$i,$this->font_width*$i+10); 
  112. $color = imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255)); 
  113. imagettftext($img,$fontsize,$angle,$x,20,$color,$this->fontpath.’/’.$this->font,substr($this->text,$i,1)); 
  114. } 
  115. imagepng($img); 
  116. //释放资源 
  117. imagedestroy($img); 
  118. imagedestroy($bghanddle); 
  119. } 
  120. } 
  121. new validimg($_SESSION['valid']); 
  122. ?> 

测试文件validtest.php,代码如下:

  1. <?php 
  2. /** 
  3. * 验证码测试 
  4. * @author  zcs 
  5. */ 
  6. session_start(); 
  7. $_SESSION['valid']= randstr(); 
  8. echo $_SESSION['valid']; 
  9.  
  10. //随机生成字符串 
  11.  
  12. function randstr($num=4) 
  13. { 
  14. $chars = ‘ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789′; 
  15. $randstr=”; 
  16. for($i=0;$i<$num;$i++) 
  17. { 
  18. $randstr.=substr($chars,rand(0,strlen($chars)),1); 
  19. } 
  20. return $randstr; 
  21. } 
  22. ?> 
  23. <img src=”validimg.php” />  
  24. 生成gif动态验证码,PHP生成GIF动画来实现动态图片验证码,以下是实现过程,ImageCode函数通过GIFEncoder类实现的GIF动画  
  25. /**    
  26.  * ImageCode 生成GIF图片验证    
  27.  * @param $string 字符串    
  28.  * @param $width 宽度    
  29.  * @param $height 高度    
  30.  * */   
  31. function ImageCode($string = '', $width = 75, $height = 25)    
  32. {    
  33.     $authstr = $string ? $string : ((time() % 2 == 0) ? mt_rand(1000, 9999) : mt_rand(10000, 99999));     
  34.         
  35.     $board_width = $width;    
  36.     $board_height = $height;    
  37.     // 生成一个32帧的GIF动画    
  38.     for($i = 0; $i < 32; $i++)    
  39.     {    
  40.         ob_start();    
  41.         $image = imagecreate($board_width, $board_height);    
  42.         imagecolorallocate($image, 0,0,0);    
  43.         // 设定文字颜色数组     
  44.         $colorList[] = ImageColorAllocate($image, 15,73,210);    
  45.         $colorList[] = ImageColorAllocate($image, 0,64,0);    
  46.         $colorList[] = ImageColorAllocate($image, 0,0,64);    
  47.         $colorList[] = ImageColorAllocate($image, 0,128,128);    
  48.         $colorList[] = ImageColorAllocate($image, 27,52,47);    
  49.         $colorList[] = ImageColorAllocate($image, 51,0,102);    
  50.         $colorList[] = ImageColorAllocate($image, 0,0,145);    
  51.         $colorList[] = ImageColorAllocate($image, 0,0,113);    
  52.         $colorList[] = ImageColorAllocate($image, 0,51,51);    
  53.         $colorList[] = ImageColorAllocate($image, 158,180,35);    
  54.         $colorList[] = ImageColorAllocate($image, 59,59,59);    
  55.         $colorList[] = ImageColorAllocate($image, 0,0,0);    
  56.         $colorList[] = ImageColorAllocate($image, 1,128,180);    
  57.         $colorList[] = ImageColorAllocate($image, 0,153,51);    
  58.         $colorList[] = ImageColorAllocate($image, 60,131,1);    
  59.         $colorList[] = ImageColorAllocate($image, 0,0,0);    
  60.         $fontcolor = ImageColorAllocate($image, 0,0,0);    
  61.         $gray = ImageColorAllocate($image, 245,245,245);     
  62.             
  63.         $color = imagecolorallocate($image, 255,255,255);    
  64.         $color2 = imagecolorallocate($image, 255,0,0);    
  65.             
  66.         imagefill($image, 0, 0, $gray);    
  67.             
  68.         $space = 15;        // 字符间距    
  69.         if($i > 0)          // 屏蔽第一帧    
  70.         {    
  71.             for ($k = 0; $k < strlen($authstr); $k++)     
  72.             {     
  73.                 $colorRandom = mt_rand(0,sizeof($colorList)-1);     
  74.                 $float_top = rand(0,4);    
  75.                 $float_left = rand(0,3);    
  76.                 imagestring($image, 6, $space * $k, $top + $float_top, substr($authstr, $k, 1), $colorList[$colorRandom]);    
  77.             }    
  78.         }    
  79.             
  80.         for ($k = 0; $k < 20; $k++)     
  81.         {     
  82.             $colorRandom = mt_rand(0,sizeof($colorList)-1);     
  83.             imagesetpixel($image, rand()%70 , rand()%15 , $colorList[$colorRandom]);     
  84.         
  85.         }    
  86.         // 添加干扰线    
  87.         for($k = 0; $k < 3; $k++)    
  88.         {    
  89.             $colorRandom = mt_rand(0, sizeof($colorList)-1);     
  90.             // $todrawline = rand(0,1);    
  91.             $todrawline = 1;    
  92.             if($todrawline)    
  93.             {    
  94.                 imageline($image, mt_rand(0, $board_width), mt_rand(0,$board_height), mt_rand(0,$board_width), mt_rand(0,$board_height), $colorList[$colorRandom]);    
  95.             }    
  96.             else     
  97.             {    
  98.                 $w = mt_rand(0,$board_width);    
  99.                 $h = mt_rand(0,$board_width);    
  100.                 imagearc($image, $board_width - floor($w / 2) , floor($h / 2), $w, $h,  rand(90,180), rand(180,270), $colorList[$colorRandom]);    
  101.             }    
  102.         }    
  103.         imagegif($image);    
  104.         imagedestroy($image);    
  105.         $imagedata[] = ob_get_contents();    
  106.         ob_clean();      
  107.         ++$i;      
  108.     }    
  109.         
  110.     $gif = new GIFEncoder($imagedata);      
  111.     Header ('Content-type:image/gif');      
  112.     echo $gif->GetAnimation();      
  113. }  
  114.  
  115. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  116. <html xmlns="http://www.w3.org/1999/xhtml">  
  117. <head>  
  118. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  119. <title>无标题文档</title>  
  120. <script language="javascript">  
  121.  function refresh_code()  
  122.  {  
  123.   form1.imgcode.src="verifycode.php?a="+Math.random();  
  124.  }  
  125. </script>  
  126. </head>  
  127. <body>  
  128. <form id="form1" name="form1" method="post" action="checkcode.php">  
  129.   <label for="code">验证码:</label>  
  130.   <input type="text" name="code" id="textfield" />  
  131.   <img id="imgcode" src="VerifyCode.php" alt="验证码" />  
  132.   <a href="javascript:refresh_code()">看不清?换一个</a>  
  133.   <input type="submit" name="button" id="button" value="提交" />  
  134. </form>  
  135. </body>  
  136. </html> 

checkcode.php文件如下:

  1. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  2. <?php  
  3. ini_set('display_errors', 'Off');  
  4. session_start();  
  5.   if((strtoupper($_POST["code"])) == strtoupper(($_SESSION["VerifyCode"]))){  
  6.  print("验证码正确,");  
  7.   }else{  
  8.     print("验证码错误,");  
  9.   }  
  10.   echo "提交的验证码:".strtoupper($_POST["code"]).",正确的验证码:".strtoupper($_SESSION["VerifyCode"]);  
  11. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表