Jerry's WIKIJerry's WIKI
概述
  • 🐞 web使用
  • 📐 常用组件
  • 💡 使用技巧
  • 🎱 规范相关
  • 🖥 工作流
  • 🛠 常用工具
  • 🌐️ 服务器
  • 📦 容器相关
  • ♨️ 编程语言
咖啡屋
  • 简体中文
  • English
GitHub
概述
  • 🐞 web使用
  • 📐 常用组件
  • 💡 使用技巧
  • 🎱 规范相关
  • 🖥 工作流
  • 🛠 常用工具
  • 🌐️ 服务器
  • 📦 容器相关
  • ♨️ 编程语言
咖啡屋
  • 简体中文
  • English
GitHub
  • 🖼 图像相关

    • 二维码
    • 条形码
    • 验证码
  • 🔐 锁相关

    • Redis分布式锁
    • 数据库悲观锁
    • 数据库乐观锁
    • 队列(单个消费)
  • 🏢 Office相关

    • 数据导出Excel
    • 数据导出Csv
  • ↔️ 加解密

    • AES
    • RSA
    • AWS4
    • RC4
  • 🍪 登录相关

    • JWT
    • Cookie
    • Session
    • Q&A
  • 📀 服务部署

    • 说明
    • 部署流程

验证码

目录

  • 安装依赖包
  • 封装工具类
  • 使用

安装依赖包

标准库地址

【注意】

如果 PHP8.0+, 需要加载最新版本依赖包。详情参见:issues#110

composer require gregwar/captcha

封装工具类

查看代码
<?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;
    }
}

使用

/**
 * 获取验证码.
 * @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();
}
编辑此页面
更新时间:
贡献者: 田朝帆, JerryTZF
Prev
条形码
Next
Redis分布式锁