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

Issues
  • 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
  • Flexible composer install, remove php dependency

    Flexible composer install, remove php dependency

    Server not always installed natively in local server like ampps, wamp, dkk. So no need php dependency

    opened by ekoisa 6
  • Update composer.json

    Update composer.json

    Please, update symfony/finder version thanks

    opened by smartynovych 5
  • Added text_color option.

    Added text_color option.

    opened by adelbert-silla 5
  • 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
  • bugfix division by zero

    bugfix division by zero

    https://github.com/Gregwar/Captcha/issues/26

    opened by whyte624 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
  • BugFix : count() func error when textColor is null

    BugFix : count() func error when textColor is null

    when count() function receive a null arg happens Warning (in PHP V7+) and Fatal error (in PHP V8+) with this pull request i tried solve this problem.thanks :)

    opened by MohsenParandvar 0
  • Can you implement phrase building and checking without using super globals?

    Can you implement phrase building and checking without using super globals?

    I have ran into a sticky wicket where I am attempting to add a simple captcha page to my site and currently within the site folder super globals are disabled. So, I am getting all sorts of errors. I attempted to enable super globals programmatically just for the needed phrase and it is giving me the error Call to a member function enable_super_globals() on null. So I was wondering if there was another way to use PhraseBuilder::comparePhrases that does not entail use of the _server global?

    Here is the important block of code where I am running into issues.

    
    $captcha = new CaptchaBuilder();
    $captcha->build();
    session_start();
    global $request;
    global $config;
    $request->enable_super_globals();
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Checking that the posted phrase match the phrase stored in the session
    if (isset($_SESSION['phrase']) && PhraseBuilder::comparePhrases($_SESSION['phrase'], $_POST['phrase'])) {
      header("Location: index.php");
    	//echo "<h1>Captcha is valid !</h1>";
        } else {
    	echo "<h1>Captcha is not valid!</h1>";
        }
        // The phrase can't be used twice
      unset($_SESSION['phrase']);
    };
    $request->disable_super_globals()
    
    

    I know this is not technically an "issue", but figured it would not hurt asking for a little help sorting this one out.

    opened by anoduck 0
  • Call to undefined function imagettfbbox()

    Call to undefined function imagettfbbox()

    here is my gd info : image php version:7.4.8

    --enable-gd-native-ttf is not available when configure in 7.3 + , so how to resolve this problem??

    opened by jonny77 1
  • [Feature Request]Add GIF type captcha

    [Feature Request]Add GIF type captcha

    GIF can increase the difficulty of recognition.

    opened by kaysonwu 1
  • both upper & lower case in v1.1.8

    both upper & lower case in v1.1.8

    In v1.1.7, getPhrase() will only return string in lower-case, while in v1.1.8, getPhrase() will return upper&lower characters. if there is a notice in README, it'll be better to prevent someone get confused after doing composer update

    opened by llxcyzgh 0
  • Can you refine the verification code style?

    Can you refine the verification code style?

    Can individual letters use different colors? Can you use other background confusion? Confused as small letters?

    E.g: https://www.php.cn/captcha.html

    opened by ZhangChengLin 7
  • Sometimes, the results of getPhrase and inline are partly inconsistent

    Sometimes, the results of getPhrase and inline are partly inconsistent

    Why sometimes the characters of getPhrase () and the characters in inline () are inconsistent, not all are wrong, but the case of one of the letters is inconsistent.

    E.g: The image base64 from inline () is processed in the browser, and the result displayed is YF7B But the result of getPhrase () is Yf7B

    why? Is it a browser issue or a code design issue?

    opened by ZhangChengLin 7
  • This class feels so bloated.  Can you split it up?

    This class feels so bloated. Can you split it up?

    https://github.com/Gregwar/Captcha/blob/4bb668e6b40e3205a020ca5ee4ca8cff8b8780c5/src/Gregwar/Captcha/CaptchaBuilder.php#L14

    This class feels so bloated. Can you split it up?

    opened by ZhangChengLin 6
  • Fatal error in PHP 7.4 : Uncaught Error: Call to undefined function Gregwar\Captcha\imagejpeg() in

    Fatal error in PHP 7.4 : Uncaught Error: Call to undefined function Gregwar\Captcha\imagejpeg() in

    Hello Guys!!!

    I see there is an error in php 7.4 version with Call to undefined function Gregwar\Captcha\imagejpeg()

    this error is coming up on line number 565 in below file vendor/gregwar/captcha/src/Gregwar/Captcha/CaptchaBuilder.php

    Can you please see it and fix it !!!

    Thanks

    opened by zakir1929 3
  • Add support for IMG_FILTER_SCATTER added in PHP 7.4

    Add support for IMG_FILTER_SCATTER added in PHP 7.4

    Example Screenshot

    I added support for IMG_FILTER_SCATTER with checks to ensure that it functions identically with older PHP versions.

    opened by hwvs 0
Owner
Grégoire Passault
Don't send me e-mail to advertise for your new products or services, thanks :)
Grégoire Passault
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 800 Jun 11, 2021
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.2k Jun 17, 2021
Plug n play avatar, turn name, email, and any other string into beautiful avatar (or gravatar), effortless.

laravolt/avatar Display unique avatar for any user based on their (initials) name. Preview Installation This package originally built for Laravel, but

Laravolt 1.5k Jun 6, 2021
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 11.9k Jun 15, 2021
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.1k Jun 13, 2021
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 856 Jun 10, 2021
This package provides an integration with FFmpeg for Laravel. Laravel's Filesystem handles the storage of the files.

Laravel FFMpeg This package provides an integration with FFmpeg for Laravel 6.0 and higher. Laravel's Filesystem handles the storage of the files. Fea

Protone Media 859 Jun 11, 2021
Create images with embedded text using advanced typography

Image with Text This class makes it super easy to render images with multiple, independently styled text blocks. You can control each text block's ali

New Media Campaigns 129 Jun 3, 2021
👤 Add your own default WordPress avatar.

Custom User Avatar WordPress currently only allows you to use custom avatars that are uploaded through Gravatar. Custom User Avatar enables you to use

David Artiss 9 Jun 4, 2021
Create material deisgn avatars for users just like Google Messager. It may not be unique but looks better than Identicon or Gravatar.

Material-Design-Avatars Create material deisgn avatars for users just like Google Messager. It may not be unique but looks better than Identicon or Gr

Canbin Lin 267 Apr 18, 2021
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 661 May 28, 2021
🌄 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.7k Jun 16, 2021
A PHP GD + TwitterOAuth demo to dynamically generate Twitter header images and upload them via the API.

A PHP GD + TwitterOAuth demo to dynamically generate Twitter header images and upload them via the API. This enables you to build cool little tricks, like showing your latest followers or sponsors, latest content creted, a qrcode to something, a progress bar for some goal, and whathever you can think of.

Erika Heidi 75 Jun 17, 2021
Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file, move it to a new directory, and returns the new source for the image.

NO LONGER MAINTAINED!!! Image Cache v. 1.0.0 Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file,

Erik Nielsen 453 Apr 16, 2021