laravel 生成验证码及验证

向右看齐 2022-03-22 10:23 605阅读 0赞

第一步:引入gregwar/captcha包:
composer require gregwar/captcha

第二步:在帮助函数中创建函数:

  1. use Gregwar\Captcha\CaptchaBuilder;
  2. use Illuminate\Http\Request;
  3. use Session;
  4. class HelperController extends Controller {
  5. //生成验证码
  6. public function captcha($tmp) {
  7. //生成验证码图片的Builder对象,配置相应属性
  8. $builder = new CaptchaBuilder;
  9. //可以设置图片宽高及字体
  10. $builder->build($width = 250, $height = 70, $font = null);
  11. //获取验证码的内容
  12. $phrase = $builder->getPhrase();
  13. //把内容存入session
  14. Session::flash('milkcaptcha', $phrase);
  15. //生成图片
  16. header("Cache-Control: no-cache, must-revalidate");
  17. header('Content-Type: image/jpeg');
  18. $builder->output();
  19. }
  20. //验证注册码的正确与否
  21. public function verifyCaptcha() {
  22. $userInput = request('captcha');
  23. if (Session::get('milkcaptcha') == $userInput) {
  24. //用户输入验证码正确
  25. return $this->outPutJson('', 200, '验证码正确!');
  26. } else {
  27. //用户输入验证码错误
  28. return $this->outPutJson('', 301, '验证码输入错误!');
  29. }
  30. }
  31. }
  32. 第三步:如果想要替换自己的验证码字体,可以在包内的Font文件夹内替换,按照格式命名即可。看这个源码就明白了,随机生成一个数字,字体命名格式如下:captcha4.ttf。一般自带的就够用了。
  33. D:\phpStudy\WWW\api.douxiaoli.com\vendor\gregwar\captcha\Font\
  34. if ($font === null) {
  35. $font = __DIR__ . '/Font/captcha' . $this->rand(0, 8) . '.ttf';
  36. }
  37. 如果前台要调用,也很简单,直接把这个接口返回的结果放到img标签里面就可以了:
  38. <img src="http://api.commas-studio.com/helper/captcha/11">

发表评论

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

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

相关阅读

    相关 验证生成

    视图函数里 > 1,导入图片,画布,画笔,画笔上的字体,定义坐标 > 2,从外部导入字体(字体导入到static静态中) > 3,随机生成验证码,验证码颜色,验证