Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

PHP 7.3 Is Now Available On Cloudways. Try Now!

How To Add reCAPTCHA to Symfony 3 Forms

Updated on October 5, 2016

5 Min Read
Reading Time: 5 minutes

Previously, I discussed how to build a REST API for use in your Symfony 3.1 projects.

Websites use different techniques and methods to validate contact, login and user registration forms. Some opt for custom validation methods while a large majority deploy third-party validation techniques.

add recaptcha in symfony 3

Google provides a well known and proven validation tool known as reCAPTCHA. In this tutorial, I will demonstrate how to add Google reCAPTCHA to a Symfony 3 registration form. Hence, if you’re looking for a Recaptcha Symfony union, you’ve got it!

Let’s get started by creating a PHPStack server on Cloudways first.

Create PHP Application and Install Symfony

The first order of business is to create an application on the web server. To make things easier to follow, I have created the following GIF of the process.

php server cloudways

Once done, login to SSH terminal by using the Master credentials. Move to public_html folder using the following command

$ cd application/{your_application_folder}/public_html

To install Symfony 3, run the following command in the SSH terminal:

$ composer create-project symfony/framework-standard-edition your_project_name "3.0"

You need to add database configurations between installations. Go to application access area and find db credentials.

In case of any issues, follow this excellent guide on Symfony 3 installation process.

Creating a Google reCAPTCHA Application

The first step is to build a Google reCAPTCHA application through the official website. Sign into the account by clicking get reCAPTCHA button, and a website registration form for the website would appear.

reCaptcha Registration

Enter an easy to remember label and the domain name(s) of the site. For the purpose of this tutorial, I will use the following staging URL of the application phpstack-21306-56790-158086.cloudwaysapps.com in the space for domains. Do not add Https:// or Http:// before the domain name. Click on Register button to get API Keys.

Site key

secret key

The site key is the public key that will be used in the frontend HTML code. The secret key is the private key required for communicating between the app and Google servers.  Both keys are required to call reCAPTCHA in the application. Google also provides a script and a div for embedding in the app. Following are the screencaps of both the script and the div respectively.

reCaptcha script

reCaptcha div

Creating a Simple ToDo Form

I will now create a simple form for adding to-dos in the database.

Create the User Entity

The User entity will save a user’s name, email and password. Since I’m already signed into the SSH terminal, I will run the following command to start Symfony’s Entity Generator:

$ php bin/console doctrine:generate:entity

Enter the entity name AppBundle:User and hit Enter and select yml as the default annotation. Now enter name, category and description in the entity fields step by step. Hit Enter to generate the entity.

generate entity

To populate the database and add a table, run the following command

$ php bin/console doctrine:schema:update --force

Create the View for Controller

It’s important to initialize the form in the view file for the controller to recognize and render the form on the screen. Go to app/Resources/views and create form.html.twig file in it. Add the following code to add reCAPTCHA and initialize the form.

{# Add reCAPTCHA api provided by website #}
<script src='https://www.google.com/reCAPTCHA/api.js'async defer></script>

{% block body %}
<h2 class=page-header>create todo with captcha</h2>
{{form_start(form)}}

 {# Add the reCAPTCHA div to show in form #}
<div class="g-reCAPTCHA" data-sitekey="6LeTXQgUAAAAAGByWkRSVeJxE274kd7zz8_ksXI2"></div>
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}

Create the Controller

The second step is to create the controller. Go to src/AppBundle/Controller and open DefaultController.php. Add the following code to the file:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

use AppBundle\Entity\Todo;

class DefaultController extends Controller
{ 
     /**
     * @Route("/form", name="homepage")
     */
   public function createAction(Request $request)
    {
        $todo = new Todo;
      
      # Add form fields
        $form = $this->createFormBuilder($todo)
        ->add('name', TextType::class, array('label'=> 'Todo Title', 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('category', TextType::class, array('label'=> 'Todo Category','attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('description', TextareaType::class, array('label'=> 'Todo Description','attr' => array('class' => 'form-control')))
        ->add('Save', SubmitType::class, array('label'=> 'Create Todo', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
        ->getForm();
        
      # Handle form and recaptcha response
        $form->handleRequest($request);
          
      # check if form is submitted and Recaptcha response is success
        if($form->isSubmitted() &&  $form->isValid() && $this->captchaverify($request->get('g-recaptcha-response'))){
            $name = $form['name']->getData();
            $category = $form['category']->getData();
            $description = $form['description']->getData();
            
      # set form data   
            $todo->setName($name);
            $todo->setCategory($category);          
            $todo->setDescription($description);                  
            
       # finally add data in database
            $sn = $this->getDoctrine()->getManager();      
            $sn -> persist($todo);
            $sn -> flush();
            
            $this->addFlash(
                'notice',
                'Todo Added'
            );
            return $this->redirectToRoute('homepage');                
      } 
           
       # check if captcha response isn't get throw a message
            if($form->isSubmitted() &&  $form->isValid() && !$this->captchaverify($request->get('g-recaptcha-response'))){
                 
            $this->addFlash(
                'error',
                'Captcha Require'
              );             
            }
            
        return $this->render('default/form.html.twig', array(
            'form' => $form->createView()  
        ));
    }
    
    # get success response from recaptcha and return it to controller
    function captchaverify($recaptcha){
            $url = "https://www.google.com/recaptcha/api/siteverify";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array(
                "secret"=>"6LeTXQgUAAAAALExcpzgCxWdnWjJcPDoMfK3oKGi","response"=>$recaptcha));
            $response = curl_exec($ch);
            curl_close($ch);
            $data = json_decode($response);     
        
        return $data->success;        
    }
}

Note that I have created a separate method captchaverify() to call reCaptcha response from the server and return it. After that, I have used the response to validate the form. You will see the Flash messages on top if records are sent with or without reCaptcha.

Test the Application

The basic architecture of the reCAPTCHA application along with the entity, controller and view are now ready for testing. Enter the URL of the application in the browser. I will use the following URL:

http://phpstack-21306-56790-161164.cloudwaysapps.com/symfony/web/app_dev.php/form

The following form will appear:

recaptcha form in symfony 3

Test application by adding records and the reCAPTCHA. As you will see, records will only add if reCAPTCHA is validated successfully. This is a basic app and can easily be used as the foundation for much complex user-validation scenarios.

Conclusion:

Now, reCAPTCHA Symfony should be easy for you. If you have any query about the tutorial, please feel free to comment below. In the upcoming installment of this series, I will discuss asset management in Symfony 3.1. Here is a short introduction and list of major topics in this Symfony 3.1 series.

Share your opinion in the comment section. COMMENT NOW

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at shahroze.nawaz@cloudways.com

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

THERE’S MORE TO READ.