PHP code example of tetthys / captcha

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

    

tetthys / captcha example snippets


use Tetthys\Captcha\Algorithms\SimpleMathCaptcha;
use Tetthys\Captcha\Services\CaptchaService;
use Tetthys\Captcha\Services\CaptchaSession;

$service = new CaptchaService(
    new SimpleMathCaptcha(),
    new CaptchaSession(),
);

// Generate a new captcha
$captcha = $service->new();
echo $captcha->question; // e.g. "3 + 5 = ?"

// Later...
$userInput = '8';
$isValid = $service->validateCurrent($userInput); // true or false

interface CaptchaAlgorithmInterface
{
    public function generate(): object; // { question, answer }
}

(new SimpleMathCaptcha())->generate();
// => (object) [ 'question' => '7 + 2 = ?', 'answer' => '9' ]

interface CaptchaValidatorInterface
{
    public function validate(string $answer, string $input): bool;
}

$session = new CaptchaSession();
$session->set('42');
echo $session->pull(); // '42' (and then removed)

$service = new CaptchaService(
    new SimpleMathCaptcha(),
    new CaptchaSession(),
);

$q = $service->new();                // -> question only
$isValid = $service->validateCurrent('7'); // checks user input vs stored answer

use Illuminate\Support\ServiceProvider;
use Tetthys\Captcha\Algorithms\SimpleMathCaptcha;
use Tetthys\Captcha\Services\CaptchaService;
use Tetthys\Captcha\Services\CaptchaSession;

final class CaptchaServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(CaptchaService::class, function () {
            return new CaptchaService(
                new SimpleMathCaptcha(),
                new CaptchaSession(),
            );
        });
    }
}

$captcha = app(CaptchaService::class)->new();        // -> { question }
$isValid = app(CaptchaService::class)->validateCurrent($request->input('captcha'));

use Tetthys\Captcha\Contracts\CaptchaAlgorithmInterface;

final class WordCaptcha implements CaptchaAlgorithmInterface
{
    public function generate(): object
    {
        $word = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ'), 0, 5);
        return (object) ['question' => $word, 'answer' => $word];
    }
}

new CaptchaService(new WordCaptcha(), new CaptchaSession());