src/AppBundle/EventListener/ReCaptchaValidationListener.php line 17

Open in your IDE?
  1. <?php
  2. namespace AppBundle\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Form\FormEvents;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class ReCaptchaValidationListener implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  12.      */
  13.     public function onKernelRequest(GetResponseEvent $event)
  14.     {
  15.         if ('login_check' !== $event->getRequest()->getPathInfo()) {
  16.             return;
  17.         }
  18.         $token $event->getRequest()->request->get('g-recaptcha-response');
  19.         if($token){
  20.             $ch curl_init();
  21.             curl_setopt($chCURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
  22.             curl_setopt($chCURLOPT_POST1);
  23.             curl_setopt($chCURLOPT_POSTFIELDShttp_build_query([
  24.                 "secret" => "6LdbupIiAAAAAGST-LJkJyGyU5lXbow0r3si9i2W",
  25.                 "response" => $token
  26.             ]));
  27.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  28.             $server_output json_decode(curl_exec($ch));
  29.             curl_close($ch);
  30.             if ($server_output->success) {
  31.                 return;
  32.             }
  33.         }
  34.         $event->setResponse(new RedirectResponse('/login'));
  35.         // get recaptcha from request and validate it.if you want to prevent request to call next event, just set response for event. $event->setResponse($response)
  36.     }
  37.     public static function getSubscribedEvents()
  38.     {
  39.         return [
  40.             KernelEvents::REQUEST => ['onKernelRequest'9]
  41.         ];
  42.     }
  43. }