当前位置:首页 > PHP教程 > php图像处理 > 列表

php编程每天必学之验证码

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-12 22:37:21 浏览: 评论:0 

php编程每天必学之验证码,php验证码图片生成以及页面实现验证码功能进行了详细的阐述,感兴趣的小伙伴们可以参考一下。

本文为大家分享了php图片验证码的实现代码,分享给大家供大家参考,具体内容如下

1.验证码图片生成

captcha.php

  1. //1.生成100*30大小的图片,默认为黑色 
  2. $image = imagecreatetruecolor(100,30); 
  3. //创建白色底图 
  4. $bgcolor = imagecolorallocate($image,255,255,255); 
  5. //用白色填充黑色 
  6. imagefill ($image,0,0,$bgcolor); 
  7.  
  8. //2.随机显示数字或字母 
  9. $captch_code = ""; 
  10. for($i=0;$i<4;$i++){ 
  11.  $fontsize=6; 
  12.  $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120)); 
  13.  $data = "abcdefghijkmnpqrstuvwxy3456789"; 
  14.  $fontcontent =substr($data,rand(0,strlen($data)),1); 
  15.  $captch_code .=$fontcontent; 
  16.  $x = ($i*100/4)+rand(5,10); 
  17.  $y = rand(5,10); 
  18.  
  19.  imagestring($image, $fontsize, $x, $y, $fontcontent,$fontcolor); 
  20. } 
  21. $_SESSION["authcode"] = $captch_code; 
  22.  
  23. //3.增加干扰 
  24. //干扰点 
  25. for($i=0;$i<100;$i++){ 
  26.  $pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200)); 
  27.  imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor); 
  28. } 
  29.  
  30. //干扰线 
  31. for($i=0;$i<2;$i++){ 
  32.  $linecolor=imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220)); 
  33.  imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor); 
  34. } 
  35.  
  36. header("content-type:image/png"); 
  37. imagepng($image); 

2.页面实现验证码功能

form.php

  1. <?php 
  2. if(isset($_POST["authcode"])){ 
  3.  session_start(); 
  4.  if(strtolower($_POST["authcode"])==$_SESSION["authcode"]){ 
  5.   echo "OK"; 
  6.  }else{ 
  7.   echo "NO"; 
  8.  } 
  9. } 
  10.  
  11. ?> 
  12. <!doctype html> 
  13. <html lang="en"> 
  14. <head> 
  15.  <meta charset="UTF-8"> 
  16.  <title>Document</title> 
  17. </head> 
  18. <body> 
  19. <form action="form.php" method="post"> 
  20.  <p>验证码图片: <img id="img" border="1" src="captcha.php?r=<?php echo rand()?>" alt=""> 
  21.  <a href="javascript:void(0)" onclick="document.getElementById('img').src='captcha.php?r'+Math.random() ">换一个</a> 
  22.  </p> 
  23.  <p><input type="text" name="authcode"></p> 
  24.  <p><input type="submit" value="提交"></p> 
  25.  
  26. </form> 
  27. </body> 
  28. </html> 

以上就是本文的全部内容,帮助大家轻松实现php图片验证码。

Tags: php验证码

分享到: