PHP code example of karewan / kncaptcha

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

    

karewan / kncaptcha example snippets


use Karewan\KnCaptcha\KnCaptcha;
use Karewan\KnCaptcha\Store;

$captcha = new KnCaptcha(
	secret: $config['captcha_secret'], // at least 32 bytes: bin2hex(random_bytes(32))
	markUsed: Store::redis($redis),
);

// GET /captcha/challenge: what the widget fetches
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode(['challenge' => $captcha->createChallenge('login')]);

// POST /login: the widget put the solution in the "kncaptcha" field
if (!$captcha->verify($_POST['kncaptcha'] ?? '', 'login')) {
	http_response_code(422);
	exit;
}

// phpredis
markUsed: fn (string $id, int $ttl): bool => $redis->set("kncaptcha:{$id}", 1, ['nx', 'ex' => $ttl]) === true,

// Laravel
markUsed: fn (string $id, int $ttl): bool => Cache::add("kncaptcha:{$id}", 1, $ttl),

// Symfony cache: not atomic, use a lock or one of the stores below

$failures = $attempts->count($ip);
$difficulty = match (true) {
	$failures < 5 => Difficulty::low(),
	$failures < 10 => Difficulty::medium(),
	default => Difficulty::high(),
};
echo json_encode(['challenge' => $captcha->createChallenge('login', $difficulty)]);
shell
composer test    # custom runner, no dependency: php tests/run.php [filter]
composer bench