Laminas (former Zend) Framework : Anti-bot Protection with CAPTCHA

Laminas (former Zend) Framework : Anti-bot Protection with CAPTCHA

Introduction

Today, when robots are a popular way to scan websites on the Internet and do some malicious actions,
the only good way to protect from them is using CAPTCHA – a randomly
generated image (or set of images) which is hard to decode for robots, but relatively easy
to decode for humans. Almost every website uses CAPTCHAs on its Login page,
on its Checkout page, or on any other web form requiring the anti-bot protection.

Laminas Framework provides support for several types of CAPTCHA: distorted noisy
images, Google’s ReCaptcha, and some other simple CAPTCHA types. It is also possible to integrate an
arbitrary CAPTCHA by writing a custom adapter class. In this article, we will describe
how to integrate three types of CAPTCHA with your Laminas website:

  • Image CAPTCHA – it is a simple yet good (but not perfect) protection
  • Google’s ReCaptcha – a very popular free CAPTCHA service
  • hCaptcha – a new free CAPTCHA service that is becoming a good alternative to Google ReCaptcha

About CAPTCHA

A CAPTCHA (stands for “Completely Automated Public Turing test to tell Computers and Humans Apart”)
is a test for determining whether the user is a human or a robot.

A simple image CAPTCHA works using the following algorithm:

  • Some secret sequence of characters is generated on the server and saved in session.
  • A distorted noisy image is generated based on the secret. The image is then displayed on the web page to site user.
  • The site user is asked to type characters from the image.
  • If the characters typed by user are the same as the secret saved in the PHP session, the test is passed.

During the last years, CAPTCHA services became very popular. One of them is Google’s ReCaptcha.
You can use its free or enterprise version. The CAPTCHA widget shows you a checkbox you need to click to prove you are a human.
As an additional measure of protection, ReCaptcha may show you several images and you will need to choose certain objects from them (e.g. only cars or planes).

There is a good alternative CAPTCHA service called hCaptcha. It is similar to ReCaptcha: they show you the checkbox you need to click,
and some images to select from. It can be used for free.

Installation

We assume you already have a website created using Laminas Framework and you want to integrate CAPTCHA
with some of your web forms. If you don’t have a website yet, you may build a simple one from scratch
with Laminas MVC Skeleton.

First, you need to install the laminas/laminas-captcha package with Composer:

composer require laminas/laminas-captcha

If you are going to use Google’s ReCaptcha, you additionally need to install the laminas/laminas-recaptcha package:

composer require laminas/laminas-recaptcha    

Using Image CAPTCHA

We will show how to use Image CAPTCHA by building a simple Sign In form. Create a file src/module/Application/Form/ImageCaptchaForm.php
and put the following PHP code into it:


described its usage with comments:
// Add the Image CAPTCHA element!
$this->add([
    'type'  => 'captcha',
    'name' => 'captcha',
    'attributes' => [
    ],
    'options' => [
        'label' => 'CAPTCHA',
        'captcha' => [
            'class' => 'Image',               // Alias of the adapter class
            'imgDir' => 'public/img/captcha', // Directory where CAPTCHA images will be stored
            'suffix' => '.png',               // Extension of CAPTCHA images
            'imgUrl' => '/img/captcha/',      // By which URL you can access CAPTCHA images
            'imgAlt' => 'CAPTCHA',            // Value of ALT attributes for images
            'font'   => './data/font/OpenSans-Regular.ttf', // Which font to use for printing the text inside of CAPTCHAs
            'fsize'  => 20,                   // Font size
            'width'  => 300,                  // Width of image 
            'height' => 80,                   // Height of image
            'expiration' => 500,              // Seconds before CAPTCHA expires
            'dotNoiseLevel' => 20,            // Noise level for dots
            'lineNoiseLevel' => 4             // Noise level for lines
        ],
    ],
]);

Image CAPTCHA requires a TTF font for printing letters and digits on the image. You can download a free font
from this website or use a font of your choice.

Create the public/img/captcha directory, so CAPTCHA images will be generated and stored in it. Ensure this
directory is writable by the web server:

sudo chown -R apache:apache public/img/captcha 

Next, we can start using the form we created. Create an action in your controller and make it look like below:

public function imageAction()
{
    $form = new Application/Form/ImageCaptchaForm();

    if($this->getRequest()->isPost()) {

        $data = $this->params()->fromPost();

        $form->setData($data);

        if($form->isValid()) {

            $data = $form->getData();
            $email = $data['email'];
            $password = $data['password'];

            // Check email and password here

            return $this->redirect()->toRoute('application',
                        ['action'=>'success']);
        }
    }

    // Pass form variable to view
    return new ViewModel([
        'form' => $form
    ]);

}

Finally, add the view template for the action:

Image CAPTCHA Demo

 

 

 

 

 

 

 

 

Enter the letters above as you see them.

 

 

 

 

If you now open the controller action in your browser, you should see the Image CAPTCHA generated:

 

Using Google ReCaptcha

To use Google ReCaptcha on your website, you first need to go to this page
and create new public and private keys.

Then create a form with ReCaptcha in the src/module/Application/Form/ReCaptchaForm.php file:

Using hCaptcha

To use hCaptcha with our website, we first need to register for free and request the site key
and a secret from this page.

Next, add an adapter class for hCaptcha, since hCaptcha is not supported by Laminas by default.
To do that, create the file src/module/Application/Form/HCaptcha.php and put the following code into it:

hCaptcha Demo

 

 

 

 

 

 

 

 

 

Note how we render the hCaptcha in HTML. You should substitute your hCaptcha site key:

 

And also note the

Now, if you open the controller action in your browser, you should see something like below:

Conclusion

In this article, we considered using CAPTCHA in your Laminas website. You use CAPTCHA with your web
forms if you want only humans to be able to submit the form. CAPTCHA is easy for humans to solve, but
robots are not sophisticated enough to bypass it. Laminas provides several CAPTCHAs. Image CAPTCHA is a
simple way that generates a distorted noisy image with some digits or letters. We also showed how to use
two free but powerful CAPTCHA services: Google's ReCaptcha and hCaptcha. You can use those services
if you find Image CAPTCHA too simple for your website.

 

Leave a Reply

Your email address will not be published. Required fields are marked *