Captcha
Index
Install Dependencies
ใWarningใ
If PHP8.0+, the latest version of the dependency package needs to be loaded. For more details, refer to: issues#110.
composer require gregwar/captcha
Encapsulate Utility Class
ๆฅ็ไปฃ็
<?php
declare(strict_types=1);
namespace App\Lib\Image;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Hyperf\Context\ApplicationContext;
use Hyperf\Redis\Redis;
class Captcha
{
/**
* redis ๅฎไพ.
* @var mixed|Redis Redisๅฎไพ
*/
private Redis $redis;
public function __construct()
{
$this->redis = ApplicationContext::getContainer()->get(Redis::class);
}
/**
* ่ทๅ้ช่ฏ
* @param string $clientUniqueCode ไธๅ็ๅฎขๆท็ซฏไฝฟ็จไธๅ็ๅฏไธๆ ่ฏ
* @return string ๆไปถๆตๅญ็ฌฆไธฒ
*/
public function getStream(string $clientUniqueCode): string
{
// ้ช่ฏ็ ้ฟๅบฆๅ่ๅด
$phrase = new PhraseBuilder(4, 'abcdefghijklmnpqrstuvwxyz123456789');
// ๅๅงๅ้ช่ฏ็
$builder = new CaptchaBuilder(null, $phrase);
// ๅๅปบ้ช่ฏ็
$builder->build();
// ่ทๅ้ช่ฏ็ ๅ
ๅฎน
$phrase = $builder->getPhrase();
$this->redis->del($clientUniqueCode);
$this->redis->set($clientUniqueCode, $phrase, ['NX', 'EX' => 300]);
return $builder->get();
}
/**
* ้ช่ฏ้ช่ฏ็
* @param string $captcha ้ช่ฏ็
* @param string $clientUniqueCode ๅฏไธ็
* @return bool ๆฏๅฆ้ช่ฏ้่ฟ
*/
public function verify(string $captcha, string $clientUniqueCode): bool
{
$cachedCaptcha = $this->redis->get($clientUniqueCode);
if ($cachedCaptcha === $captcha) {
$this->redis->del($clientUniqueCode);
return true;
}
return false;
}
}
Usage
/**
* ่ทๅ้ช่ฏ็ .
* @param ImageRequest $request ้ช่ฏ่ฏทๆฑ็ฑป
* @return MessageInterface|ResponseInterface ๆตๅผๅๅบ
*/
#[Scene(scene: 'captcha')]
#[GetMapping(path: 'captcha/show')]
public function getCaptcha(ImageRequest $request): MessageInterface|ResponseInterface
{
$ip = $this->getRequestIp();
$uniqueCode = $request->input('captcha_unique_code');
$unique = $ip . '_' . $uniqueCode;
$captchaString = (new Captcha())->getStream($unique);
return $this->response->withHeader('Content-Type', 'image/png')
->withBody(new SwooleStream($captchaString));
}
/**
* ้ช่ฏ้ช่ฏ็ .
* @param ImageRequest $request ้ช่ฏ่ฏทๆฑ็ฑป
* @return array ['code' => '200', 'msg' => 'ok', 'status' => true, 'data' => []]
*/
#[Scene(scene: 'verify')]
#[GetMapping(path: 'captcha/verify')]
public function verifyCaptcha(ImageRequest $request): array
{
$ip = $this->getRequestIp();
$uniqueCode = $request->input('captcha_unique_code');
$unique = $ip . '_' . $uniqueCode;
$captchaCode = $request->input('captcha');
$isSuccess = (new Captcha())->verify($captchaCode, $unique);
return $this->result->setData(['is_success' => $isSuccess])->getResult();
}