PHP code example of petalbranch / icon-captcha

1. Go to this page and download the library: Download petalbranch/icon-captcha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

petalbranch / icon-captcha example snippets




use Illuminate\Support\Facades\Redis; // 示例使用 Laravel Redis Facade

// 1. 生成验证码
// 参数可选:icon_captcha_generate(宽度, 高度, 图标数, 干扰数);
$captcha = icon_captcha_generate(320, 200, 4, 2);

// 返回结构详解:
// [
//    'id'     => 'ic.65b7...', 
//    'image'  => 'base64_string...', // 主图 Base64 (不含前缀)
//    'mime'   => 'image/webp',       // 主图 MIME 类型 (image/webp 或 image/png)
//    'icons'  => ['base64...', ...], // 提示图标 Base64 数组 (固定为 PNG 格式)
//    'answer' => [[x,y,X,Y], ...]    // 正确答案坐标范围 (敏感数据! 勿传前端)
// ]

$id = $captcha['id'];
$answer = $captcha['answer'];

// 2.【关键】存储答案到服务端缓存(例如 Redis 或 Session)
// 建议设置较短的过期时间,例如 2-5 分钟
Redis::setex("captcha:{$id}", 300, json_encode($answer));

// 3. 返回给前端(排除 answer 字段)
$response = [
    'id'    => $id,
    'image' => $captcha['image'], // 前端: src="data:{{mime}};base64,{{image}}"
    'mime'  => $captcha['mime'],  // 这里会返回 image/webp 或 image/png
    'icons' => $captcha['icons']  // 前端: 遍历展示这组小图标提示用户点击
];

header('Content-Type: application/json');
echo json_encode($response);

  
  
  use Illuminate\Support\Facades\Redis;
  
  // 获取请求参数
  $params = $_POST; // 或 $request->all();
  
  $id = $params['id'] ?? '';
  $clickPositions = $params['click_positions'] ?? []; 
  // $clickPositions 格式示例: 
  // [[10, 20], [150, 60], ...] 
  // 或 
  // [['x'=>10, 'y'=>20], ['x'=>150, 'y'=>60], ...]
  
  if (empty($id) || empty($clickPositions)) {
      // 抛出错误...
  }
  
  // 1. 从缓存中取出正确答案
  $cacheKey = "captcha:{$id}";
  $cachedAnswer = Redis::get($cacheKey);
  
  if (!$cachedAnswer) {
      echo json_encode(['success' => false, 'message' => '验证码已过期或不存在']);
      exit;
  }
  
  $answer = json_decode($cachedAnswer, true);
  
  // 2. 执行验证
  // 注意参数顺序:(前端点击坐标, 正确答案坐标)
  $isVerified = icon_captcha_verify($clickPositions, $answer);
  
  if ($isVerified) {
      // ✅ 验证通过
      // 建议验证成功后立即删除缓存,防止重放攻击
      Redis::del($cacheKey);
      echo json_encode(['success' => true, 'message' => '验证通过']);
  } else {
      // ❌ 验证失败
      echo json_encode(['success' => false, 'message' => '验证失败,请重试']);
  }
  



// 1. 获取加密的 payload
$ciphertext = $_POST['ciphertext'];
$id = $_POST['id'];

// 2. 解密 (需与前端加密算法一致)
try {
    // 这里的 decrypt 是你项目中封装的解密方法
    $jsonStr = MySecurity::decrypt($ciphertext, 'YOUR_SECRET_KEY');
    
    // 解析为数组
    $clickPositions = json_decode($jsonStr, true);
    
    if (!is_array($clickPositions)) {
        throw new Exception("无效的数据格式");
    }
} catch (Exception $e) {
    // 解密失败,直接视为验证不通过
    die(json_encode(['success' => false, 'message' => '非法请求']));
}

// 3. 从缓存获取正确答案
$answer = json_decode(Redis::get("captcha:$id"), true);

// 4. 调用库函数进行验证 (传入解密后的原始坐标数组)
if (icon_captcha_verify($clickPositions, $answer)) {
    // 验证通过
} else {
    // 验证失败
}

// 指定存放 jpg/png 图片的文件夹路径
$bgFolder = __DIR__ . '/assets/backgrounds';

$captcha = icon_captcha_generate(
    backgroundImageFolder: $bgFolder
);



use Petalbranch\IconCaptcha\Contract\IconSetInterface;

class MyCustomIconSet implements IconSetInterface
{
    protected string $fontFilePath;

    public function __construct(string $fontFilePath)
    {
        $this->fontFilePath = $fontFilePath;
    }

    /**
     * 定义你的字体图标映射
     * 键名:图标的别名(方便调试)
     * 键值:图标在 ttf 文件中的十六进制 Unicode 码
     */
    public function getIcons(): array
    {
        return [
            "star"   => "e001", 
            "heart"  => "e002",
            "camera" => "e003",
            // ... 更多图标
        ];
    }

    /**
     * 实现随机获取逻辑
     */
    public function getRandom(int $count = 4): array
    {
        $icons = $this->getIcons();
        $keys = array_rand($icons, $count);

        if (!is_array($keys)) $keys = [$keys];

        $result = [];
        foreach ($keys as $key) {
            $hex = $icons[$key];
            // 将十六进制转换为 UTF-8 字符
            $result[$key] = mb_chr(hexdec($hex), 'UTF-8');
        }
        return $result;
    }

    public function getFontPath(): string
    {
        return $this->fontFilePath;
    }
}

// 1. 实例化你的自定义类
$myIconSet = new MyCustomIconSet('/path/to/your-custom-font.ttf');

// 2. 传入生成函数
$captcha = icon_captcha_generate(
    iconSet: $myIconSet
);