PHP code example of phgors / gocaptcha

1. Go to this page and download the library: Download phgors/gocaptcha 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/ */

    

phgors / gocaptcha example snippets


use Phgors\GoCaptcha\Click\ClickBuilder;
use Phgors\GoCaptcha\Assets\DefaultAssets;
use Phgors\GoCaptcha\Click\ClickValidator;

$captcha = ClickBuilder::make()
    ->setBackgrounds(DefaultAssets::backgrounds())
    ->setFonts(DefaultAssets::fonts())
    ->setChars(DefaultAssets::chineseChars())
    ->build();

$data = $captcha->generate();

// 返回给前端
$payload = $data->toArray(); // ['masterImage' => ..., 'thumbImage' => ...]
// $data->getDots() 自行存 Session / Cache 作为答案

// 校验(下一次请求,用户点击的点)
$ok = ClickValidator::validate($storedDots, $userPoints, $padding = 10);

use Phgors\GoCaptcha\Slide\SlideBuilder;
use Phgors\GoCaptcha\Slide\GraphImage;
use Phgors\GoCaptcha\Assets\DefaultAssets;
use Phgors\GoCaptcha\Slide\SlideValidator;

$graphs = array_map(function ($dir) {
    return new GraphImage("$dir/overlay.png", "$dir/mask.png", "$dir/shadow.png");
}, DefaultAssets::tileSets());

$captcha = SlideBuilder::make()
    ->setBackgrounds(DefaultAssets::backgrounds())
    ->setGraphs($graphs)
    ->build(); // 或 ->buildRegion() 区域拖拽模式

$data = $captcha->generate();
$payload = $data->toArray();     // masterImage + tileImage
$block = $data->getBlock();      // 存 Session / Cache

$ok = SlideValidator::validate($block, $userX, $userY, $padding = 5);

use Phgors\GoCaptcha\Rotate\RotateBuilder;
use Phgors\GoCaptcha\Assets\DefaultAssets;
use Phgors\GoCaptcha\Rotate\RotateValidator;

$captcha = RotateBuilder::make()
    ->setBackgrounds(DefaultAssets::backgrounds())
    ->build();

$data = $captcha->generate();
$payload = $data->toArray();
$angle = $data->getBlock()->getAngle(); // 存 Session / Cache

$ok = RotateValidator::validate($angle, $userAngle, $padding = 8);

use Phgors\GoCaptcha\Click\ClickOptions;
use Phgors\GoCaptcha\Base\Size;
use Phgors\GoCaptcha\Base\RangeVal;

$options = (new ClickOptions())
    ->withImageSize(new Size(300, 220))        // 主图尺寸
    ->withThumbSize(new Size(150, 40))         // 缩略图尺寸
    ->withRangeLen(new RangeVal(4, 5))         // 生成字符个数范围
    ->withRangeVerifyLen(new RangeVal(2, 4))   // 需点击个数范围
    ->withRangeSize(new RangeVal(26, 34))      // 字号范围
    ->withDisplayShadow(true);                 // 文字阴影

$captcha = ClickBuilder::make()
    ->setBackgrounds(DefaultAssets::backgrounds())
    ->setFonts(DefaultAssets::fonts())
    ->setChars(DefaultAssets::chineseChars())
    ->setOptions($options)
    ->build();