PHP生成加减算法方式的验证码实例

下面小编就为大家分享一篇PHP生成加减算法方式的验证码实例,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧。

这是在网上找的一个demo,我加入了一部分代码,可以使用。

这里需要说明一下,我们调用这个验证码类应该在一个单独的控制器方法中使用。

生成的图片的算法是用代码生成的,然后把计算值存入session中。

验证的时候是获取用户的输入值,然后取出服务端的值进行对比

  1. <?php
  2. namespace mobile\components;
  3. /**
  4. * @author fenghuo
  5. *
  6. * 改造的加减法验证类
  7. * 使用示例 VerifyCode::get(1,2);
  8. * 验证示例 VerifyCode::check($code);
  9. */
  10. class VerifyCode
  11. {
  12. /**
  13. * php验证码
  14. */
  15. public static function get($one,$two,$prefix = '', $font_size = 28)
  16. {
  17. //文件头...
  18. ob_get_clean();
  19. header("Content-type: image/png;charset=utf-8;");
  20. //创建真彩色白纸
  21. $width = $font_size*5;
  22. $height = $font_size+1;
  23. $im = @imagecreatetruecolor($width, $height) or die("建立图像失败");
  24. //获取背景颜色
  25. $background_color = imagecolorallocate($im, 255, 255, 255);
  26. //填充背景颜色
  27. imagefill($im, 0, 0, $background_color);
  28. //获取边框颜色
  29. $border_color = imagecolorallocate($im, 200, 200, 200);
  30. //画矩形,边框颜色200,200,200
  31. imagerectangle($im,0,0,$width - 1, $height - 1,$border_color);
  32. //逐行炫耀背景,全屏用1或0
  33. for($i = 2;$i < $height - 2;$i++) {
  34. //获取随机淡色
  35. $line_color = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255));
  36. //画线
  37. imageline($im, 2, $i, $width - 1, $i, $line_color);
  38. }
  39. //设置印上去的文字
  40. $firstNum = $one;
  41. $secondNum = $two;
  42. $actionStr = $firstNum > $secondNum ? '-' : '+';
  43. //获取第1个随机文字
  44. $imstr[0]["s"] = $firstNum;
  45. $imstr[0]["x"] = rand(2, 5);
  46. $imstr[0]["y"] = rand(1, 4);
  47. //获取第2个随机文字
  48. $imstr[1]["s"] = $actionStr;
  49. $imstr[1]["x"] = $imstr[0]["x"] + $font_size - 1 + rand(0, 1);
  50. $imstr[1]["y"] = rand(1,5);
  51. //获取第3个随机文字
  52. $imstr[2]["s"] = $secondNum;
  53. $imstr[2]["x"] = $imstr[1]["x"] + $font_size - 1 + rand(0, 1);
  54. $imstr[2]["y"] = rand(1, 5);
  55. //获取第3个随机文字
  56. $imstr[3]["s"] = '=';
  57. $imstr[3]["x"] = $imstr[2]["x"] + $font_size - 1 + rand(0, 1);
  58. $imstr[3]["y"] = 3;
  59. //获取第3个随机文字
  60. $imstr[4]["s"] = '?';
  61. $imstr[4]["x"] = $imstr[3]["x"] + $font_size - 1 + rand(0, 1);
  62. $imstr[4]["y"] = 3;
  63. //文字
  64. $text = '';
  65. //写入随机字串
  66. for($i = 0; $i < 5; $i++) {
  67. //获取随机较深颜色
  68. $text_color = imagecolorallocate($im, rand(50, 180), rand(50, 180), rand(50, 180));
  69. $text .= $imstr[$i]["s"];
  70. //画文字
  71. imagechar($im, $font_size, $imstr[$i]["x"], $imstr[$i]["y"], $imstr[$i]["s"], $text_color);
  72. }
  73. session_start();
  74. $_SESSION[$prefix.'verifycode'] = $firstNum > $secondNum ? ($firstNum - $secondNum) : ($firstNum + $secondNum);
  75. //显示图片
  76. ImagePng($im);
  77. //销毁图片
  78. ImageDestroy($im);
  79. }
  80. public static function check($code)
  81. {
  82. if(trim($_SESSION[$prefix.'verifycode']) == trim($code)) {
  83. return true;
  84. } else {
  85. return false;
  86. }
  87. }
  88. }