Search by

websk / php-captcha

websk

Captcha generator and Slim route handlers

Package info

github.com/websk/php-captcha

pkg:composer/websk/php-captcha

Statistics

Installs: 148

Dependents: 2

Suggesters: 0

Stars: 0

Open Issues: 0

3.0.0 2026-10-12 17:48 UTC

This package is auto-updated.

Last update: 2026-10-12 17:51:03 UTC


README

websk/php-captcha generates PNG CAPTCHA images and provides Slim 4 route handlers for generating and validating them.

Requirements

  • PHP 8.3 or later, including PHP 8.5
  • GD with FreeType support
  • Mbstring
  • PHP sessions
  • Slim 4

Installation

Install the package with Composer:

composer require websk/php-captcha

The package is available on Packagist.

Slim integration

Register the CAPTCHA routes on an existing Slim application:

<?php

use Slim\Factory\AppFactory;
use WebSK\Captcha\CaptchaRoutes;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

CaptchaRoutes::register($app);

$app->run();

This adds two named GET routes:

Route Name Response
/captcha/generate captcha:generate image/png
/captcha/check_ajax captcha:check_ajax JSON true or false

Display the generated image and use the captcha field for the entered code:

<img src="/captcha/generate" alt="CAPTCHA">
<input type="text" name="captcha" inputmode="numeric" autocomplete="off">

The validation route accepts the code from parsed request data or the query string:

GET /captcha/check_ajax?captcha=12345

The expected value is stored in the server-side PHP session and is removed after a non-empty validation attempt. Generate a new image before retrying. When no session is active, the package starts one with strict mode, an HttpOnly cookie, and SameSite=Lax by default. Existing session settings are used when the application starts the session first.

Request handlers pass their PSR-7 request directly to Captcha::check(). Code outside a handler can do the same:

$valid = \WebSK\Captcha\Captcha::check($request);

Demo

Run the bundled Slim application:

composer install
cd public
php -S localhost:8000

Then open http://localhost:8000. The root route redirects to the generated CAPTCHA image.

Development

Run syntax checks, PHPUnit, and PHPStan together:

composer check

The individual commands are also available:

composer lint
composer test
composer phpstan

Upgrade from 2.x

Version 3.0 stores the expected CAPTCHA value in the server-side session. The 2.x client-side CAPTCHA cookie is no longer trusted. Applications must have PHP sessions available and should pass the current PSR-7 request to Captcha::check().

License

This project is licensed under the MIT License.