Adding Captcha to Anchor

I was getting a lot of spam messages on this blog, so I decided it was long overdue to add a captcha to the form submission. Which means a fun dive into the completely undocumented world of Anchor CMS!

The first thing that you'll need to do is get a No Captcha API key from https://www.google.com/recaptcha/admin. Simply fill out your website name, and you should be set. Follow the client side set up, by adding the script to the theme 'partial/header.php' file, and adding the div to the theme 'article.php' file. These are both in place in my theme, Folium, which is here on GitHub.

Next, you need to do the server side verification. This goes in the anchor/routes/site.php under the 'Post a comment' section (somewhere around line 130), after the validation lines, but before the other error flashing section.

// Captcha processing
$captcha = Input::get(array('g-recaptcha-response'))['g-recaptcha-response'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 
         http_build_query([
            'secret' => '<captcha_secret_from_api_key>',
            'response' => $captcha
         ]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$verification = json_decode(curl_exec($ch), true);
curl_close($ch);

if (!$verification['success']) {
    Input::flash();

    Notify::error(['email' => ['You must verify your post with the captcha.']]);

    return Response::redirect($posts_page->slug . '/' . $slug . '#comment');
}

And there you go! You should be all set up.

5 comments

  • Joe

    Thank you for this. Extremely helpful. I was in the same spammy situation and your guide was exactly what I needed.

  • Marco

    Thanks a lot, was looking for this :)

  • Marek

    Nice, i was excatly looking for this. In my case, I paste code around line 175 in site.php.

  • test name

    Just checking to see if this works. Thanks!

  • Tom

    Hmm having trouble: returns the error "you must verify your post with the captcha" whether the recaptcha is completed successfully or not.