A Beginner’s Guide to Lock WordPress Page with Captcha – WordPress Tutorial

By | September 19, 2019

WordPress captcha plugin can add captcha in wordpress comments form, login form. However, most of them can not be added in wordpress pages to lock our contents. In this tutorial, we will introduce how to add a wordpress captcha for a wordpress page.

Download a php captcha

We use a php captcha in wordpress. You can download it in here.

Download

Then put captcha files in your wordpress theme folder.

wordpress captcha files

Add captcha for wordpress page

You can add an example code below to you wordpress page.

<div id="captcha_box">
    <?php
        $img_captcha = get_bloginfo('template_directory');
        $home = get_bloginfo('home');
    ?>
    <form action="<?php echo $home;?>/confirm.php/" method="post">
        <p>Are you a robot?</p>
        <p>
        <img id="captcha" src="<?php echo $img_captcha;?>/securimage/securimage_show.php" alt="CAPTCHA Image" />
        <a href="#" onclick="document.getElementById('captcha').src = '<?php echo $img_captcha;?>/securimage/securimage_show.php?' + Math.random(); return false">[ Different Image ]</a>
        <input type="text" name="captcha_code" size="10" maxlength="6" /></p>
        <p><input type="submit" value="Unlock" /></p>
    </form>
</div>

The demo of this code likes:

wordpress php captcha demo

How to check the cpatcha code of user input is correct?

If you use confirm.php to validate the cpatcha code of user input. You can do like this:

Start session at the first line of confirm.php

<?php session_start(); ?>

Only allow confirm.php receive post method

if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
	header('Allow: POST');
	header('HTTP/1.1 405 Method Not Allowed');
	header('Content-Type: text/plain');
	echo "only allow post";
	exit;
}

Import securimage.php

require_once dirname(__FILE__) . '/securimage/securimage.php';

Validate the cpatcha

$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
  // you should handle the error so that the form processor doesn't continue
  // or you can use the following code if there is no validation or you do not know how
  echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
  exit;
}else{
  echo "successfully";
}

If the cpatcha of user input is correct, this file will print successfully.

Leave a Reply

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