Yii 2 使用 RESTful 的图形验证码与服务端验证 [ 技术分享 ]
namespace api\modules\v1\actions\captcha;
use Yii;
use micsay\captcha\CaptchaBuilder;
class IndexAction extends \yii\rest\Action
{
public $width = 76;
public $height = 38;
public $foreColor = 0x2299EE; //0x2040A0
public $transparent = true;
/**
* @inheritdoca
*/
public function run()
{
$captcha = new CaptchaBuilder();
$captcha->fixedVerifyCode = YII_ENV_TEST ? 'testme' : null;
$captcha->width = $this->width;
$captcha->height = $this->height;
//$captcha->backColor = 0x000000;
//$captcha->padding = 5;
//$captcha->offset = 4;
$captcha->minLength = 4;
$captcha->maxLength = 4;
$captcha->foreColor = $this->foreColor;
$captcha->transparent = $this->transparent;
$captcha->testLimit = 3;
$base64 = $captcha->base64();
$code = $captcha->getPhrase();
$code = strtolower($code);
Yii::$app->cache->set($this->generateCacheKey($code), $code, 60);
return $base64;
}
/**
* @param string $code
* @return bool
* @throws Exception
*/
public function validate($code)
{
if (Yii::$app->cache->get($this->generateCacheKey($code)) === $code) {
Yii::$app->cache->delete($this->generateCacheKey($code));
return true;
}
return false;
}
/**
* @return string
*/
private function generateCacheKey($code)
{
return base64_encode(Yii::$app->request->getRemoteIP().Yii::$app->request->getUserAgent().$code);
}
}
tangniyuqi 成都
注册时间:2011-12-21
最后登录:2022-08-12
在线时长:18小时1分
最后登录:2022-08-12
在线时长:18小时1分
- 粉丝4
- 金钱370
- 威望0
- 积分550