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->getUrl('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(): void
    {
        $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

MethodDescriptionExample
setFontAbsolute monospace font file path in ttf format/var/www/magework/fonts/courier.ttf
setColorText color in hexadecimal#ffffff
setBackgroundBackground color in hexadecimal#000000
setCharsAllowed characters (included in the font)abcdefghijkmnopqrstuvwxyz23456789
setLengthText length5
setWidthImage width in px105
setHeightImage height in px40
setFontSizeFont size20
setPaddingTopImage padding top in px28
setPaddingLeftImage padding left in px12
setAngleText orientation angle5
<?php

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