Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Captcha Laravel Package

cadoles/captcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require gregwar/captcha-bundle
    

    (No manual registration needed if using Symfony Flex.)

  2. First Use Case: Add the CaptchaType to a form in your controller:

    use Gregwar\CaptchaBundle\Type\CaptchaType;
    
    $builder->add('captcha', CaptchaType::class);
    

    This renders a CAPTCHA image + input field by default.

  3. Where to Look First:

    • Configuration: Check config/packages/gregwar_captcha.yaml (auto-generated if needed).
    • Form Integration: Review the Symfony Form Theming docs for customization.
    • Routing: If using as_url, add the bundle’s routes to config/routes.yaml:
      gregwar_captcha_routing:
          resource: "@GregwarCaptchaBundle/Resources/config/routing/routing.yml"
      

Implementation Patterns

Core Workflows

  1. Basic Form Integration:

    // Controller
    $form = $this->createFormBuilder()
        ->add('name', TextType::class)
        ->add('captcha', CaptchaType::class, [
            'length' => 6,
            'reload' => true, // Adds a "refresh" link
        ])
        ->getForm();
    
    • Key Options:
      • length: Adjust CAPTCHA complexity (default: 5).
      • reload: Adds a "refresh" link (useful for UX).
      • disabled: Set to true in dev environments to skip validation.
  2. Dynamic Configuration: Override defaults per form or globally in config/packages/gregwar_captcha.yaml:

    gregwar_captcha:
        width: 200
        height: 60
        charset: "abcdefghjkmnpqrstuvwxyz23456789" # Exclude ambiguous chars
        distortion: false # Disable distortion for testing
    
  3. Multi-CAPTCHA Forms: Use session_key to isolate CAPTCHAs on the same page:

    $builder->add('captcha1', CaptchaType::class, ['session_key' => 'form1_captcha']);
    $builder->add('captcha2', CaptchaType::class, ['session_key' => 'form2_captcha']);
    
  4. File-Based CAPTCHAs: Enable as_file for IE6/7 compatibility or multi-server setups:

    $builder->add('captcha', CaptchaType::class, [
        'as_file' => true,
        'image_folder' => 'custom_captcha_folder',
    ]);
    
    • Note: Requires web_path config (default: %kernel.project_dir%/public).
  5. URL-Based Generation: For distributed systems, use as_url:

    $builder->add('captcha', CaptchaType::class, [
        'as_url' => true,
        'whitelist_key' => 'custom_whitelist_key',
    ]);
    
    • Routing: Ensure the /generate-captcha/{key} route is accessible.
  6. Validation: Handle validation in your controller:

    if (!$form->isValid()) {
        $errors = $form->getErrors(true);
        if ($errors->has('captcha')) {
            // Log or notify about CAPTCHA failure
        }
    }
    
  7. Theming: Customize the Twig template (templates/form/captcha_widget.html.twig):

    {% block captcha_widget %}
        <div class="captcha-container">
            <img src="{{ captcha_code }}" alt="CAPTCHA" />
            <input type="text" name="{{ form.vars.name }}" />
            <a href="#" onclick="this.parentNode.querySelector('img').src='/generate-captcha?reload'; return false;">
                Refresh
            </a>
        </div>
    {% endblock %}
    

Gotchas and Tips

Pitfalls

  1. Session Key Conflicts:

    • If using multiple CAPTCHAs on one page without session_key, the second CAPTCHA may overwrite the first.
    • Fix: Always specify session_key for multi-CAPTCHA forms.
  2. File-Based CAPTCHA Cleanup:

    • The bundle runs garbage collection randomly (controlled by gc_freq). Old files may linger if expiration is too high.
    • Fix: Manually trigger cleanup in a cron job or command:
      use Gregwar\CaptchaBundle\Generator\CaptchaGenerator;
      $generator = new CaptchaGenerator();
      $generator->cleanup();
      
  3. IE6/7 Compatibility:

    • Embedded CAPTCHAs (as_file=false, as_url=false) may fail in IE6/7 due to XSS restrictions.
    • Fix: Use as_file=true or as_url=true for legacy support.
  4. Distortion and Background Images:

    • If background_images is set, ignore_all_effects must be true to avoid rendering artifacts.
    • Fix: Add to config:
      gregwar_captcha:
          background_images: ["%kernel.project_dir%/path/to/image1.png", ...]
          ignore_all_effects: true
      
  5. Bypass Code Security:

    • The bypass_code option is useful for testing but should never be used in production.
    • Fix: Remove or set to null in production:
      gregwar_captcha:
          bypass_code: null
      
  6. Routing Conflicts:

    • The default /generate-captcha/{key} route may conflict with existing routes.
    • Fix: Prefix the route in config/routes.yaml:
      gregwar_captcha_routing:
          resource: "@GregwarCaptchaBundle/Resources/config/routing/routing.yml"
          prefix: /_captcha
      
  7. Font Paths:

    • Custom fonts require absolute paths (e.g., %kernel.project_dir%/public/fonts/captcha.ttf).
    • Fix: Use the font option:
      $builder->add('captcha', CaptchaType::class, [
          'font' => '%kernel.project_dir%/public/fonts/Roboto-Bold.ttf',
      ]);
      
  8. Humanity Check:

    • The humanity option skips CAPTCHAs after a correct submission, but does not reset on form errors.
    • Fix: Reset the session key manually if needed:
      $request->getSession()->remove('captcha_humanity_check');
      

Debugging Tips

  1. Check Session Storage:

    • CAPTCHA codes are stored in the session under keys like captcha_<session_key>.
    • Debug: Dump the session in a controller:
      dump($request->getSession()->all());
      
  2. Validate Image Generation:

    • If CAPTCHAs appear blank, check:
      • File permissions for as_file mode.
      • GD library support (phpinfo()).
      • Custom background_images paths.
  3. Log Validation Errors:

    • Override the invalid_message to include debug info:
      gregwar_captcha:
          invalid_message: "CAPTCHA failed. Expected: {{ expected }}, Got: {{ submitted }}"
      
  4. Test Distortion:

    • Disable distortion (distortion: false) to verify CAPTCHA readability:
      gregwar_captcha:
          distortion: false
      

Extension Points

  1. Custom Validation: Override the validator in a form type:

    use Symfony\Component\Validator\Constraints as Assert;
    
    $builder->add('captcha', CaptchaType::class, [
        'constraints' => [
            new Assert\Callback(function ($value, ExecutionContextInterface $context) {
                // Custom logic (e.g., check against a database)
            }),
        ],
    ]);
    
  2. Event Listeners: Hook into CAPTCHA generation via Symfony events (e.g., kernel.request):

    // src/EventListener/CaptchaListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        if ($event->isMasterRequest()) {
            $request = $event->getRequest();
            if ($request->isXmlHttpRequest() && $request->get('_route') === 'generate_captcha') {
                // Modify CAPTCHA behavior dynamically
            }
        }
    }
    
  3. Dynamic Configuration: Use a compiler pass to override settings at runtime:

    // src/DependencyInjection/Compiler/CaptchaPass.php
    public function process(ContainerBuilder $container) {
        $definition = $container->findDefinition('gregwar_captcha.generator');
        $definition->replaceArgument(0, [
            'width' => $this->get
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor