验证码相关组件

gregwar/captcha

项目地址 https://github.com/Gregwar/Captcha

安装

  1. composer require gregwar/captcha 1.*

使用

建立文件 app/controller/Login.php

  1. <?php
  2. namespace app\controller;
  3. use support\Request;
  4. use Gregwar\Captcha\CaptchaBuilder;
  5. class Login
  6. {
  7. /**
  8. * 测试页面
  9. */
  10. public function index(Request $request)
  11. {
  12. return view('login/index');
  13. }
  14. /**
  15. * 输出验证码图像
  16. */
  17. public function captcha(Request $request)
  18. {
  19. // 初始化验证码类
  20. $builder = new CaptchaBuilder;
  21. // 生成验证码
  22. $builder->build();
  23. // 将验证码的值存储到session中
  24. $request->session()->set('captcha', strtolower($builder->getPhrase()));
  25. // 获得验证码图片二进制数据
  26. $img_content = $builder->get();
  27. // 输出验证码二进制数据
  28. return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
  29. }
  30. /**
  31. * 检查验证码
  32. */
  33. public function check(Request $request)
  34. {
  35. // 获取post请求中的captcha字段
  36. $captcha = $request->post('captcha');
  37. // 对比session中的captcha值
  38. if (strtolower($captcha) !== $request->session()->get('captcha')) {
  39. return json(['code' => 400, 'msg' => '输入的验证码不正确']);
  40. }
  41. return json(['code' => 0, 'msg' => 'ok']);
  42. }
  43. }

建立模版文件app/view/login/index.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>验证码测试</title>
  6. </head>
  7. <body>
  8. <form method="post" action="/login/check">
  9. <img src="/login/captcha" /><br>
  10. <input type="text" name="captcha" />
  11. <input type="submit" value="提交" />
  12. </form>
  13. </body>
  14. </html>

进入页面http://127.0.0.1:8787/login 界面类似如下: 验证码相关组件 - 图1