PHP Captcha library

Overview

Captcha

Captchas examples paypal

Installation

With composer :

{
    ...
    "require": {
        "gregwar/captcha": "1.*"
    }
}

Usage

You can create a captcha with the CaptchaBuilder :

<?php

use Gregwar\Captcha\CaptchaBuilder;

$builder = new CaptchaBuilder;
$builder->build();

You can then save it to a file :

<?php

$builder->save('out.jpg');

Or output it directly :

<?php

header('Content-type: image/jpeg');
$builder->output();

Or inline it directly in the HTML page:

<img src="<?php echo $builder->inline(); ?>" />

You'll be able to get the code and compare it with a user input :

<?php

// Example: storing the phrase in the session to test for the user 
// input later
$_SESSION['phrase'] = $builder->getPhrase();

You can compare the phrase with user input:

if($builder->testPhrase($userInput)) {
    // instructions if user phrase is good
}
else {
    // user phrase is wrong
}

API

You can use theses functions :

  • __construct($phrase = null), constructs the builder with the given phrase, if the phrase is null, a random one will be generated
  • getPhrase(), allow you to get the phrase contents
  • setDistortion($distortion), enable or disable the distortion, call it before build()
  • isOCRReadable(), returns true if the OCR can be read using the ocrad software, you'll need to have shell_exec enabled, imagemagick and ocrad installed
  • buildAgainstOCR($width = 150, $height = 40, $font = null), builds a code until it is not readable by ocrad
  • build($width = 150, $height = 40, $font = null), builds a code with the given $width, $height and $font. By default, a random font will be used from the library
  • save($filename, $quality = 80), saves the captcha into a jpeg in the $filename, with the given quality
  • get($quality = 80), returns the jpeg data
  • output($quality = 80), directly outputs the jpeg code to a browser
  • setBackgroundColor($r, $g, $b), sets the background color to force it (this will disable many effects and is not recommended)
  • setBackgroundImages(array($imagepath1, $imagePath2)), Sets custom background images to be used as captcha background. It is recommended to disable image effects when passing custom images for background (ignore_all_effects). A random image is selected from the list passed, the full paths to the image files must be passed.
  • setInterpolation($interpolate), enable or disable the interpolation (enabled by default), disabling it will be quicker but the images will look uglier
  • setIgnoreAllEffects($ignoreAllEffects), disable all effects on the captcha image. Recommended to use when passing custom background images for the captcha.
  • testPhrase($phrase), returns true if the given phrase is good
  • setMaxBehindLines($lines), sets the maximum number of lines behind the code
  • setMaxFrontLines($lines), sets the maximum number of lines on the front of the code

If you want to change the number of character, you can call the phrase builder directly using extra parameters:

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

// Will build phrases of 3 characters
$phraseBuilder = new PhraseBuilder(4)

// Will build phrases of 5 characters, only digits
$phraseBuilder = new PhraseBuilder(5, '0123456789');

// Pass it as first argument of CaptchaBuilder, passing it the phrase
// builder
$captcha = new CaptchaBuilder(null, $phraseBuilder);

You can also pass directly the wanted phrase to the builder:

// Building a Captcha with the "hello" phrase
$captcha = new CaptchaBuilder('hello');

Complete example

If you want to see an example you can have a look at he demo/form.php, which uses demo/session.php to render a captcha and check it after the submission

Symfony Bundle

You can have a look at the following repository to enjoy the Symfony 2 bundle packaging this captcha generator : https://github.com/Gregwar/CaptchaBundle

Yii2 Extension

You can use the following extension for integrating with Yii2 Framework : https://github.com/juliardi/yii2-captcha

License

This library is under MIT license, have a look to the LICENSE file

Comments
  • Blank image

    Blank image

    Hello guys

    Autoload installed via composer... all is well. I also created a temp directory, writable in the same directory where the files of captcha are.

    The result is a blank image :-(

    The code is

    	$builder = new CaptchaBuilder;
    	$builder->build();
    	echo "<pre>"; print_r($builder); echo "</pre>"; exit;
    	header('Content-type: image/jpeg');
    	$builder->output();
    	exit;
    
    

    When i uncomment the line starting with "echo", i get a blank image and the result of the print_r (the echo line) is as follows:

    What am I doing wrong?

    Gregwar\Captcha\CaptchaBuilder Object
    (
        [fingerprint:protected] => Array
            (
                [0] => 0
                [1] => 207
                [2] => 221
                [3] => 228
                [4] => 2
                [5] => 253
                [6] => 155
                [7] => 239
                [8] => 0
                [9] => 26
                [10] => 20
                [11] => 97
                [12] => 32
                [13] => 3
                [14] => 240
                [15] => 154
                [16] => 163
                [17] => 1
                [18] => 14
                [19] => 39
                [20] => 145
                [21] => 9
                [22] => 2
                [23] => 1
                [24] => 61
                [25] => 56
                [26] => 69
                [27] => 8
                [28] => 5
                [29] => -3
                [30] => 2
                [31] => 0
                [32] => 0
                [33] => 4
                [34] => 2
                [35] => -6
                [36] => -4
                [37] => 3
                [38] => 0
                [39] => 4
                [40] => 1
                [41] => 77
                [42] => 37
                [43] => 3
                [44] => 0
                [45] => 107
                [46] => 14
                [47] => 45
                [48] => 29
                [49] => 3
                [50] => 1
                [51] => 65
                [52] => 19
                [53] => 79
                [54] => 13
                [55] => 1
                [56] => 121
                [57] => 28
                [58] => 7
                [59] => 46
                [60] => 0
                [61] => 0
                [62] => -6
                [63] => 3
            )
    
        [useFingerprint:protected] => 
        [textColor:protected] => Array
            (
            )
    
        [backgroundColor:protected] => 
        [backgroundImages:protected] => Array
            (
            )
    
        [contents:protected] => Resource id #3
        [phrase:protected] => 3jfj9
        [builder:protected] => Gregwar\Captcha\PhraseBuilder Object
            (
                [length] => 5
                [charset] => abcdefghijklmnpqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
            )
    
        [distortion:protected] => 1
        [maxFrontLines:protected] => 
        [maxBehindLines:protected] => 
        [maxAngle:protected] => 8
        [maxOffset:protected] => 5
        [interpolation:protected] => 1
        [ignoreAllEffects:protected] => 
        [allowedBackgroundImageTypes:protected] => Array
            (
                [0] => image/png
                [1] => image/jpeg
                [2] => image/gif
            )
    
        [tempDir] => temp/
        [background] => 13622756
    )
    
    opened by venkytt 10
  • Division by zero

    Division by zero

    Hello, I have recently begun to see some of that's just such a message in the log

    2015/06/08 15:41:56 [error] 23082
    0: *8471087 FastCGI sent in stderr: "PHP message: PHP Warning: Division by zero in /var/www/vendor/gregwar/captcha/CaptchaBuilder.php on line 321" 
    request: "GET /_gcb/generate-captcha/gcb_captcha?n=1433767309?1589940139 HTTP/1.1", 
    

    VERSION v1.1

    Thank you!

    opened by radli 8
  • Why Finder 3.0 ?

    Why Finder 3.0 ?

    Is there anything that prevents it from working with Finder 2.8?

    I am using this package through gregwar/captcha-bundle, which will work with Symfony 2.8. However, gregwar/captcha requires Finder 3.0 or above. As the result, I get gregwar/captcha v1.1.3 which is not compatible with PHP 7, while Symfony 2.8 is.

    opened by nkornev 4
  • php7 error: Parameter must be an array or an object that implements C…

    php7 error: Parameter must be an array or an object that implements C…

    …ountable in CaptchaBuilder.php on line 333

    I got this error using xampp with php7 under windows 10 64bit.

    Parameter must be an array or an object that implements Countable in CaptchaBuilder.php on line 333

    I fixed it by declaring $textColor as array() at line 29.

    opened by sandropons 4
  • text_color works only in global config.yml ?

    text_color works only in global config.yml ?

    Hi I'm tring to put the text_color parameter in the form definition as the follow exemple: $builder-> add(...) ... ->add('captcha', 'captcha', array('text_color' => array(255,0,0) )) ...

    But seems that it takes only the global config in the config.yml : .... gregwar_captcha: width: 100 height: 50 quality: 20 background_color: [255, 255, 255] text_color: [255, 0, 0] ...

    Can you check please ? Thanx Andrea

    opened by apirastru 4
  • Add the option of custom background images for the captcha

    Add the option of custom background images for the captcha

    This PR updates the captcha library to enable custom background images for the captcha.

    todo:

    • [x] - add custom background image option

    Related PR: https://github.com/Gregwar/CaptchaBundle/pull/81

    opened by lackovic10 4
  • in php 7.2 . count(null) get a warning 7.2中的count(null) 时报警告

    in php 7.2 . count(null) get a warning 7.2中的count(null) 时报警告

    hi man, php 7.2 version ,CaptchBuilder 333 line, count(null) has warning ,i know error_reporting setting ,but wish you fix this bug.

    你好,我在php 7.2 版本使用这个组件,但是出现了错误警告,导致不能生成验证码,我知道可以定义 error_report 错误级别忽略,但是本着严谨的态度来说,希望可以修正这个错误。

    opened by yangmeishu 3
  • I created Yii Extension for this library

    I created Yii Extension for this library

    Hi, thanks for developing this library. I want to tell you that I've made an extension for Yii framework based on this library. Here is the repository yii2-captcha. I hope you like it. If there are any problem please file an issue in that repository.

    Thank you.

    opened by juliardi 3
  • Options to limit the number of lines to draw on captcha text

    Options to limit the number of lines to draw on captcha text

    Hi,

    I've added 2 options to limit (or disable) the number of lines to draw on the captcha text.

    I'll send a PR for the bundle too.

    Hope you find it useful.

    opened by bftanase 3
  • Is that better to add an accessory function to get captcha's unique id?

    Is that better to add an accessory function to get captcha's unique id?

    Before I submit a pull request, just want to make sure whether it's necessary.

    With usage of capture, we also need save the phrase to validate user input. Usually we may use session or a cache component. Well, if we choose to use cache, we also need a cache key for each capture. Thanks to the fingerprint property, we can simply use md5(json_encode($captcha->getFingerprint())) or md5(implode('', $captcha->getFingerprint())) to generate an unique key as the cache key.

    As mentioned above, whether it's better to add an accessory function called getToken(), just like this:

        public function getToken()
        {
            if (empty($this->getFingerprint())) {
                throw new \Exception('Captcha token can only be accessed after built');
            }
            
            return md5(implode('', $this->getFingerprint()));
        }
    
    opened by demokn 2
  • bug count() php 7.2

    bug count() php 7.2

    screen shot 2017-12-01 at 3 22 10 pm

    PHP 7.2 Symfony 3.4 CaptchaBundle 2.0.3

    What about to create new release with this https://github.com/Gregwar/Captcha/commit/db934bae040e72999f0a31333c3ed48f0250b638 patch ?

    opened by andreybolonin 2
  • requirements incompatible with php and composer version and require ext-gd *

    requirements incompatible with php and composer version and require ext-gd *

    Hi,

    I have a problem to install this library. When I run : $ composer require gregwar/captcha

    I have this error : Package gregwar/captcha has requirements incompatible with your PHP version, PHP extensions and
    Composer version:
    - gregwar/captcha v1.1.9 requires ext-gd * but it is not present.

    I have php 8.1.1 and composer 2.3.5 versions and I have loaded ext-gd * in composer.json : $ composer require "ext-gd:*" --ignore-platform-reqs

    "require": { "phpmailer/phpmailer": "^6.6", "ext-gd": "*" }

    I have reload my VsCode But I have this error again.

    Thanks for your time ! Sorry for my english and have a nice day !

    opened by leni-mv 1
  • Fork

    Fork

    Hey there, I just released v2 of my fork. I migrated issues & open PRs, added some new features, fixed bugs, added GIF & PNG support, some helper functions & extended its test suite - today I saw your statement in #102 that it's been a long time and I guess you've got many other things on your plate ..

    Many thanks for this library, cheers

    S1SYPHOS

    opened by S1SYPHOS 13
  • Font licenses

    Font licenses

    Hello, I am interested in packaging this library for inclusion in Debian GNU/Linux. To comply with the Debian Free Software Guidelines, we need to ascertain the licensing/copyright of all files. However, I do not see any information for the six captcha fonts. Would you please share some background on their provenance and some sort of statement from their creators that allows them to be distributed. Thanks! --Joe

    opened by jnahmias 4
  • PHP Deprecated:  Implicit conversion from float -- to int loses precision in CaptchaBuilder.php on line 365

    PHP Deprecated: Implicit conversion from float -- to int loses precision in CaptchaBuilder.php on line 365

    Not sure this is still being maintained, but after I upgraded my PHP version to 8.1 I am seeing this error message.

    PHP Deprecated: Implicit conversion from float 42.5 to int loses precision in CaptchaBuilder.php on line 365 PHP Deprecated: Implicit conversion from float 3.3333333333333335 to int loses precision in CaptchaBuilder.php on line 608

    Seems to be related to:

    https://php.watch/versions/8.1/deprecate-implicit-conversion-incompatible-float-string

    opened by sscotti 3
Owner
Grégoire Passault
Don't send me e-mail to advertise for your new products or services, thanks :)
Grégoire Passault
ImageWorkshop is a PHP5.3+ library that helps you to manage images based on GD library

================================ ImageWorkshop class ================================ Summary and features Really flexible and easy-to-use PHP class t

Clément Guillemain 855 Sep 22, 2022
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.

Image Optimizer This library is handy and very easy to use optimizer for image files. It uses optipng, pngquant, jpegoptim, svgo and few more librarie

Piotr Śliwa 872 Sep 28, 2022
PHP 5.3 Object Oriented image manipulation library

Imagine Tweet about it using the #php_imagine hashtag. Image manipulation library for PHP 5.3 inspired by Python's PIL and other image libraries. Requ

Bulat Shakirzyanov 4.3k Sep 27, 2022
This is a class of php QR Code, This library helps you generate QR codes in a jiffy.

This is a class of php QR Code, This library helps you generate QR codes in a jiffy.

null 58 Jun 30, 2022
A library using PHP to generate QRCode from https://www.qrcode-monkey.com free

PHP Class Generate Free QRCode ?? A library using PHP to generate QRCode from https://www.qrcode-monkey.com free ✋ NOTE: Do not generate too many QRCo

Nguyen Truong Nguyen 46 Sep 14, 2022
PHP library to resize, scale and crop images.

PHP library to resize, scale and crop images.

Gumlet 1.1k Sep 24, 2022
PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

PHP Image Editor PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options ! ✨ Supporting ⭐ Star this repos

Franck Alary 14 Sep 22, 2022
Goldbach Algorithms Mask is a PHP library developed for Symfony for apply a mask to strings.

Goldbach Algorithms Mask (fondly nicknamed GoldMask) is a PHP library developed for Symfony for apply a mask to strings.

Goldbach Algorithms 1 Oct 30, 2021
PHP Thumb is a light-weight image manipulation library aimed at thumbnail generation

PHP Thumb NOTICE - This project was recently updated to 2.0 and is PSR-0 compliant and supports Composer integration. Some parts of the documentation

Ian Selby 984 Jul 27, 2022
PEL: PHP Exif Library

PHP Exif Library - library for reading and writing Exif headers in JPEG and TIFF files using PHP.

null 259 Sep 14, 2022
PHP Library for generating SVG avatars based on React Avataaars

PHP library for Avataaars PHP Library for generating SVG avatars based on React Avataaars.

null 5 Apr 16, 2022
Extensionless PHP Graphic User Interface library

PHP can be more than a "Web Language", it's a fast language, with a cross platform interpreter and a good CLI. GUI is a natural step for completing this ecosystem.

Gabriel Rodrigues Couto 2.2k Sep 14, 2022
Wonderfully easy on-demand image manipulation library with an HTTP based API.

Glide Glide is a wonderfully easy on-demand image manipulation library written in PHP. Its straightforward API is exposed via HTTP, similar to cloud i

The League of Extraordinary Packages 2.3k Sep 27, 2022
Symfony Bundle to assist in imagine manipulation using the imagine library

LiipImagineBundle PHPUnit PHP-CS-Fixer Coverage Downloads Release This bundle provides an image manipulation abstraction toolkit for Symfony-based pro

Liip 1.6k Sep 21, 2022
BaconQrCode is a port of QR code portion of the ZXing library

QR Code generator Introduction BaconQrCode is a port of QR code portion of the ZXing library. It currently only features the encoder part, but could l

Bacon 1.4k Sep 29, 2022
PHPExif is a library which gives you easy access to the EXIF meta-data of an image

PHPExif v0.6.4 PHPExif is a library which gives you easy access to the EXIF meta-data of an image. PHPExif serves as a wrapper around some native or C

null 131 Aug 4, 2022
PHP Image Manipulation

Intervention Image Intervention Image is a PHP image handling and manipulation library providing an easier and expressive way to create, edit, and com

null 12.8k Sep 22, 2022
🌄 Perceptual image hashing for PHP

ImageHash A perceptual hash is a fingerprint of a multimedia file derived from various features from its content. Unlike cryptographic hash functions

Jens Segers 1.8k Sep 27, 2022
GifCreator is a PHP class that creates animated GIF from multiple images

================================ GifCreator ================================ GifCreator is a PHP class to create animated GIF from multiple images For

Clément Guillemain 318 Sep 18, 2022