PHP生成简单计算的验证码,模仿CSDN

比眉伴天荒 2022-08-09 17:56 231阅读 0赞

其实跟之前我发表的汉字验证码和英文单词加数字验证码差不多,只是多了一些逻辑的计算而已,我也是每次看到CSDN的这个验证码好奇,所以自己造了一个,大体看起来还不错,也比较符合日常的网站提交的验证。

代码如下:

  1. <?php
  2. if(!isset($_SESSION)){
  3. session_start();
  4. }
  5. $image = imagecreatetruecolor(200, 60);
  6. //设置验证码颜色 imagecolorallocate(int im, int red, int green, int blue);
  7. $bgcolor = imagecolorallocate($image,255,255,255);
  8. //区域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的区域着色,col 表示欲涂上的颜色
  9. imagefill($image, 0, 0, $bgcolor);
  10. //设置 计算的数字和操作符号
  11. $num = array('零','一','二','三','四','五','六','七','八','九');
  12. //操作符号
  13. $oper = array('+'=>'加','-'=>'减','*'=>'乘');
  14. $fontface = 'simkai.ttf';
  15. $fontcontent = $num[array_rand($num,1)].';';
  16. $fontcontent.= $oper[array_rand($oper,1)].';';
  17. $fontcontent.= $num[array_rand($num,1)].';';
  18. $fontcontent.='等于?';
  19. $arr = explode(';',$fontcontent);
  20. for($i=0;$i<4;$i++){
  21. //设置字体颜色,随机颜色 ,0-120深颜色
  22. $fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120));
  23. imagettftext($image, mt_rand(20,24),0,(30*$i+20),mt_rand(30,35),$fontcolor,$fontface,$arr[$i]);
  24. }
  25. $s_1 = array_keys($num,$arr[0]);
  26. $s_2 = array_keys($oper,$arr[1]);
  27. $s_3 = array_keys($num,$arr[2]);
  28. //计算结果
  29. switch($s_2[0]){
  30. case '+':$ret = $s_1[0]+$s_3[0];break;
  31. case '-':$ret = $s_1[0]-$s_3[0];break;
  32. case '*':$ret = $s_1[0]*$s_3[0];break;
  33. }
  34. //存到session,作为提交表单的验证
  35. $_SESSION['code'] = $ret;
  36. //增加干扰元素,设置雪花点
  37. for($i=0;$i<200;$i++){
  38. //设置点的颜色,50-200颜色比数字浅,不干扰阅读
  39. $pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));
  40. //imagesetpixel — 画一个单一像素
  41. imagesetpixel($image, rand(1,199), rand(1,59), $pointcolor);
  42. }
  43. //设置头部,image/png
  44. header('Content-Type: image/png');
  45. imagepng($image);
  46. imagedestroy($image);
  47. ?>

测试结果:

Center

Center 1

希望可以帮助到大家。

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读