MageWork

Back to home

Captcha

Display the PNG captcha image

On the page class containing the form, add a method to generate a captcha and store the text in a session variable:

<?php

declare(strict_types=1);

class Acme_Page_Contact extends Core_Page
{
    public function getCaptcha(): string
    {
        $captcha = new Captcha();

        App::session()->set('captcha', $captcha->getText());

        return $captcha->inline();
    }
}

Display the captcha image in the form:

<form action="<?= $this->getBaseUrl('contact/post/') ?>" method="post">
    <img src="<?= $this->getCaptcha() ?>" alt="This is a textual captcha" />
    <input type="text" name="secure" value="" />

    <input type="submit" value="Submit" />
</form>

Validate the captcha

When the form is submitted, check the captcha's validity:

<?php

declare(strict_types=1);

class Acme_Page_Contact_Post extends Core_Page
{
    public function execute(): string
    {
        $dataPost = $this->dataPost();

        $captcha = App::session()->pull('captcha');

        if ($dataPost->getData('secure') !== $captcha) {
            $this->setErrorMessage('Captcha is not correct');
            $this->redirect('contact.html');
        }
        
        // Form Processing
    }
}

Captcha customization

Method Description Example
setFont Absolute monospace font file path in ttf format /var/www/magework/fonts/courier.ttf
setColor Text color in hexadecimal #ffffff
setBackground Background color in hexadecimal #000000
setChars Allowed characters (included in the font) abcdefghijkmnopqrstuvwxyz23456789
setLength Text length 5
setWidth Image width in px 105
setHeight Image height in px 40
setFontSize Font size 20
setPaddingTop Image padding top in px 28
setPaddingLeft Image padding left in px 12
setAngle Text orientation angle 5
<?php

$captcha = new Captcha();
$captcha->setColor('#ffffff')->setBackground('#000000');