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

Symfony Captcha Bundle Laravel Package

captcha-com/symfony-captcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require captcha-com/symfony-captcha-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Captcha\Symfony\CaptchaBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference CaptchaSymfonyCaptchaBundle
    

    Update config/packages/captcha.yaml with your BotDetect API key (free tier available).

  3. First Use Case Generate a CAPTCHA in a controller:

    use Captcha\Symfony\CaptchaManager;
    
    public function showForm(CaptchaManager $captchaManager)
    {
        $captcha = $captchaManager->create('MyCaptcha');
        return $this->render('form.html.twig', [
            'captcha' => $captcha->getHtml(),
        ]);
    }
    

    Render in Twig:

    {{ captcha }}
    

Implementation Patterns

Core Workflows

  1. Form Integration Validate CAPTCHA in a form type:

    use Captcha\Symfony\Validator\Constraints as CaptchaAssert;
    
    class ContactType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('name')
                ->add('email')
                ->add('captcha', CaptchaType::class, [
                    'mapped' => false,
                    'captcha_name' => 'ContactFormCaptcha',
                ]);
        }
    }
    

    Add validation constraint:

    use CaptchaAssert\ValidCaptcha;
    
    #[ValidCaptcha('ContactFormCaptcha')]
    public $captcha;
    
  2. Dynamic CAPTCHA Generation Generate CAPTCHAs per-user or per-action:

    $captchaManager->create('UserRegistration_' . $userId);
    
  3. API-Based Validation Validate CAPTCHA responses without forms:

    $isValid = $captchaManager->validate('MyCaptcha', $userInput);
    

Advanced Patterns

  • Custom Themes: Extend Captcha\Symfony\CaptchaManager to inject custom themes:
    # config/packages/captcha.yaml
    captcha:
        themes:
            custom: '%kernel.project_dir%/public/captcha/themes/custom'
    
  • Rate Limiting: Use Symfony’s rate limiter middleware to throttle CAPTCHA requests:
    # config/packages/framework.yaml
    framework:
        rate_limits:
            captcha:
                limit: 5/minute
    
  • Event-Driven CAPTCHA: Listen for CAPTCHA events (e.g., CaptchaGeneratedEvent) to log or analyze CAPTCHA usage:
    use Captcha\Symfony\Event\CaptchaGeneratedEvent;
    use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
    
    #[AsEventListener(event: CaptchaGeneratedEvent::class)]
    public function onCaptchaGenerated(CaptchaGeneratedEvent $event) {
        // Log or track CAPTCHA generation
    }
    

Gotchas and Tips

Common Pitfalls

  1. API Key Misconfiguration

    • Issue: CAPTCHAs fail silently if the API key is invalid or expired.
    • Fix: Enable debug mode in captcha.yaml to log errors:
      captcha:
          debug: true
      
    • Verify the key at BotDetect Dashboard.
  2. Captcha Name Collisions

    • Issue: Reusing the same captcha_name across forms can cause validation failures.
    • Fix: Use unique names (e.g., ContactFormCaptcha, LoginFormCaptcha).
  3. Caching Headaches

    • Issue: Pre-generated CAPTCHAs may not reflect real-time changes (e.g., theme updates).
    • Fix: Regenerate CAPTCHAs dynamically or clear cache:
      $captchaManager->clear('MyCaptcha');
      
  4. Twig Template Overrides

    • Issue: Custom Twig templates for CAPTCHA may break if not properly namespaced.
    • Fix: Override the default template path:
      # config/packages/captcha.yaml
      captcha:
          templates:
              default: 'bundles/yourbundle/captcha/default.html.twig'
      

Debugging Tips

  • Validate Manually: Use the BotDetect Debugger to test CAPTCHAs.
  • Check Headers: Ensure X-Requested-With or other headers aren’t blocking CAPTCHA requests.
  • Log Responses: Enable logging for CAPTCHA API responses:
    captcha:
        logging: true
    

Extension Points

  1. Custom Validators Extend the default validator to add business logic:

    use Captcha\Symfony\Validator\CaptchaValidator;
    
    class CustomCaptchaValidator extends CaptchaValidator
    {
        public function validate($value, Constraint $constraint)
        {
            // Custom logic (e.g., blacklist certain CAPTCHAs)
            return parent::validate($value, $constraint);
        }
    }
    

    Register in services.yaml:

    Captcha\Symfony\Validator\CaptchaValidator:
        alias: App\Validator\CustomCaptchaValidator
    
  2. Async Validation Offload CAPTCHA validation to a background job (e.g., Symfony Messenger):

    use Captcha\Symfony\Message\ValidateCaptchaMessage;
    
    $bus->dispatch(new ValidateCaptchaMessage('MyCaptcha', $userInput));
    
  3. Multi-Factor CAPTCHA Combine with other security layers (e.g., Symfony’s VoteListener):

    use Symfony\Component\Security\Http\AccessMapInterface;
    
    class CaptchaAccessMap implements AccessMapInterface
    {
        public function getAccessRules()
        {
            return [
                'ROLE_ADMIN' => null,
                'ROLE_USER'  => 'captcha.validate',
            ];
        }
    }
    
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.
terminal42/code-quality-tools
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