vaibhavpandeyvpz/ank
Composer 安装命令:
composer require vaibhavpandeyvpz/ank
包简介
Simple and customizable captcha generation library, runs on PHP >= 8.2.
README 文档
README
A simple, customizable, and modern CAPTCHA generation library for PHP 8.2+. Generate text-based or mathematics-based CAPTCHAs with full control over appearance, fonts, colors, and distortion.
Ank (
अंक) means "Number" in Hindi
Features
- 🎨 Two CAPTCHA Types: Text-based alphanumeric codes or simple math problems
- 🎭 Highly Customizable: Colors, fonts, size, quality, and text distortion
- 🔒 Secure: Uses cryptographically secure random number generation
- 🎯 One-Time Validation: CAPTCHA answers are automatically removed after validation
- 🖼️ 12 Beautiful Fonts: Hand-picked Google Fonts included
- 🚀 Modern PHP: Built with PHP 8.2+ features (enums, match expressions, strict types)
- 📦 Zero Dependencies: Only requires PHP with GD extension
- ✅ Well Tested: Comprehensive test suite with high code coverage
Installation
Install via Composer:
composer require vaibhavpandeyvpz/ank
Requirements
- PHP >= 8.2
- GD extension with FreeType support (for font rendering)
Quick Start
Basic Usage
<?php use Ank\CaptchaGenerator; use Ank\MathCaptchaGenerator; // Create a text-based CAPTCHA generator $captcha = new CaptchaGenerator(); // Generate and display the CAPTCHA image header('Content-Type: image/jpeg'); echo $captcha->getCaptcha(); // Later, validate user input if ($captcha->isValid($_POST['captcha_code'])) { // CAPTCHA is valid echo "Verification successful!"; } else { // CAPTCHA is invalid echo "Invalid CAPTCHA code."; }
Mathematics CAPTCHA
<?php use Ank\MathCaptchaGenerator; // Create a math-based CAPTCHA generator $captcha = new MathCaptchaGenerator(); // Generate and display the math problem header('Content-Type: image/jpeg'); echo $captcha->getCaptcha(); // Validate the answer (user provides numeric answer) if ($captcha->isValid($_POST['answer'])) { echo "Correct answer!"; }
Advanced Usage
Customizing Appearance
The CAPTCHA image can be fully customized using a fluent interface:
<?php use Ank\CaptchaGenerator; use Ank\Font; $captcha = new CaptchaGenerator(); $image = $captcha->getCaptcha() ->setBackgroundColor('#000000') // Black background ->setForegroundColor('#FFFFFF') // White text ->setFont(Font::BANGERS) // Use Bangers font ->setSize(300, 100) // 300x100 pixels ->setQuality(100) // Maximum JPEG quality ->setDistortion(15, 8); // More distortion (angle, offset) header('Content-Type: image/jpeg'); echo $image;
Configuring Text CAPTCHA Length
<?php use Ank\CaptchaGenerator; $captcha = new CaptchaGenerator(); $captcha->setLength(8); // Generate 8-character codes $image = $captcha->getCaptcha();
Using Custom Storage
By default, CAPTCHA answers are stored in $_SESSION. You can provide a custom storage array:
<?php use Ank\CaptchaGenerator; $customStorage = []; $captcha = new CaptchaGenerator($customStorage); // The CAPTCHA answer will be stored in $customStorage $captcha->getCaptcha('my_captcha_id');
Multiple CAPTCHAs
You can generate multiple CAPTCHAs with different IDs:
<?php use Ank\CaptchaGenerator; $captcha = new CaptchaGenerator(); // Generate multiple CAPTCHAs $image1 = $captcha->getCaptcha('login_form'); $image2 = $captcha->getCaptcha('registration_form'); $image3 = $captcha->getCaptcha('contact_form'); // Validate each independently if ($captcha->isValid($_POST['login_captcha'], 'login_form')) { // Login form CAPTCHA is valid }
Available Fonts
The library includes 12 fonts from Google Fonts:
use Ank\Font; // All available fonts Font::ACME Font::BANGERS Font::BARRIO Font::BREE_SERIF Font::FRECKLE_FACE Font::GOCHI_HAND Font::LUCKIEST_GUY Font::PANGOLIN Font::RALEWAY Font::RIGHTEOUS Font::ROBOTO_SLAB Font::SANSITA // Get a random font $randomFont = Font::random(); // Get all fonts $allFonts = Font::all();
Color Formats
Colors can be specified in multiple formats:
$image->setBackgroundColor('#FFFFFF'); // 6-digit hex with # $image->setBackgroundColor('FFFFFF'); // 6-digit hex without # $image->setBackgroundColor('#FFF'); // 3-digit hex with # $image->setBackgroundColor('FFF'); // 3-digit hex without #
API Reference
CaptchaGenerator
Text-based CAPTCHA generator.
Methods:
getCaptcha(string $id = 'default'): CaptchaImageInterface- Generate a new CAPTCHAisValid(string $input, string $id = 'default'): bool- Validate user inputsetLength(int $length): static- Set the length of generated codes
MathCaptchaGenerator
Mathematics-based CAPTCHA generator.
Methods:
getCaptcha(string $id = 'default'): CaptchaImageInterface- Generate a new math problemisValid(string $input, string $id = 'default'): bool- Validate the answer
CaptchaImage
CAPTCHA image object with customization methods.
Methods:
getImage(): string- Generate and return JPEG image datasetBackgroundColor(string $hex): static- Set background colorsetForegroundColor(string $hex): static- Set text colorsetFont(Font $font): static- Set fontsetSize(int $width, int $height): static- Set image dimensionssetQuality(int $quality): static- Set JPEG quality (0-100)setDistortion(int $angle, int $offset): static- Set text distortionsetText(string $text): static- Set the text to display
Error Handling
The library throws Ank\Exception\ImageGenerationException if image generation fails:
<?php use Ank\CaptchaGenerator; use Ank\Exception\ImageGenerationException; try { $captcha = new CaptchaGenerator(); $image = $captcha->getCaptcha(); echo $image->getImage(); } catch (ImageGenerationException $e) { // Handle image generation failure error_log('CAPTCHA generation failed: ' . $e->getMessage()); // Fallback or error page }
Security Considerations
- One-Time Use: CAPTCHA answers are automatically removed after validation to prevent replay attacks
- Secure Random: Uses
random_int()for cryptographically secure random number generation - Session Storage: By default uses PHP sessions, but you can provide custom storage
- Case Sensitive: Text CAPTCHAs are case-sensitive by design
Examples
Complete Form Example
<?php // captcha.php - Generate CAPTCHA image session_start(); use Ank\CaptchaGenerator; $captcha = new CaptchaGenerator(); header('Content-Type: image/jpeg'); echo $captcha->getCaptcha('form_captcha');
<?php // form-handler.php - Validate form submission session_start(); use Ank\CaptchaGenerator; $captcha = new CaptchaGenerator(); if ($captcha->isValid($_POST['captcha'], 'form_captcha')) { // Process form echo "Form submitted successfully!"; } else { echo "Invalid CAPTCHA. Please try again."; }
AJAX Example
<?php // api/captcha.php session_start(); use Ank\CaptchaGenerator; $captcha = new CaptchaGenerator(); $image = $captcha->getCaptcha('ajax_captcha'); header('Content-Type: image/jpeg'); echo $image;
// client-side fetch("/api/captcha.php") .then((response) => response.blob()) .then((blob) => { const img = document.getElementById("captcha-image"); img.src = URL.createObjectURL(blob); });
Testing
Run the test suite:
composer test
Or with PHPUnit directly:
vendor/bin/phpunit
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Fonts are hand-picked from Google Fonts and are used in accordance with their licenses.
Author
Vaibhav Pandey
- GitHub: @vaibhavpandeyvpz
- Email: contact@vaibhavpandey.com
Changelog
See GitHub Releases for the changelog.
vaibhavpandeyvpz/ank 适用场景与选型建议
vaibhavpandeyvpz/ank 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 55 次下载、GitHub Stars 达 1, 最近一次更新时间为 2017 年 02 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「generator」 「image」 「random」 「captcha」 「mathematics」 「ank」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 vaibhavpandeyvpz/ank 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 vaibhavpandeyvpz/ank 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 vaibhavpandeyvpz/ank 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Memio's PrettyPrinter, used to generate PHP code from given Model
Yii2 LightBox image galary widget uses Lightbox v2.10.0 by Lokesh Dhakar
The Yii2 extension uses jQuery jquery.carousel-1.1.min.js and makes image carousel from php array of structure defined.
Faker Japanese is a Faker provider that generates fake Japanese related data for you.
Gambling Algorithms for Certification.
The Yii2 extension uses jQuery PrettyPhoto and OwlCarousel js and makes image galary from php array of structure defined.
统计信息
- 总下载量: 55
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 7
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2017-02-01

