CodeImgGenerate.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace common\helpers;
  3. use yii\caching\Cache;
  4. use yii\captcha\CaptchaAction;
  5. class CodeImgGenerate extends CaptchaAction
  6. {
  7. private $verifycode;
  8. public function __construct($id, $controller)
  9. {
  10. parent::__construct($id, $controller);
  11. $this->init();
  12. // 更多api请访问yii\captcha\CaptchaAction类文档
  13. // 这里可以初始化默认样式
  14. $this->maxLength = 4; // 最大显示个数
  15. $this->minLength = 4; // 最少显示个数
  16. $this->backColor = 0x000000; // 背景颜色
  17. $this->foreColor = 0x00ff00; // 字体颜色
  18. $this->width = 100; // 宽度
  19. $this->height = 58; // 高度
  20. $this->backColor = Util::captcha_color(1); // 背景颜色
  21. $this->foreColor = Util::captcha_color(2); // 字体颜色
  22. $this->padding = 0; // 间距
  23. $this->offset = 4; // 字符之间的偏移量
  24. }
  25. /**
  26. * [返回图片二进制]
  27. * @return [type] [description]
  28. */
  29. public function inline()
  30. {
  31. return $this->renderImage($this->getPhrase());
  32. }
  33. /**
  34. * [返回图片验证码]
  35. * @return [type] [description]
  36. */
  37. public function getPhrase()
  38. {
  39. if(!$this->verifycode){
  40. }
  41. $this->verifycode = (string)rand(1234, 9999);
  42. \Yii::$app->cache->set($this->getSessionKey() . '/' . $this->verifycode, $this->verifycode);
  43. return $this->verifycode;
  44. }
  45. public function validate($input, $caseSensitive = false)
  46. {
  47. $code = \Yii::$app->cache->get($this->getSessionKey() . '/' . $input);
  48. $valid = strcasecmp($input, $code) === 0;
  49. return $valid;
  50. }
  51. }
  52. ?>