Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

3 Steps Simple PHP Captcha Script (Free Download)

INTRODUCTION
STOP NASTY SPAM

Welcome to a tutorial on how to create a simple PHP captcha. Have a website that is constantly being spammed by angry troll flamer keyboard warriors? Time to put in some security and prevention measures – A captcha will do the job nicely, and this guide will walk you through how to create a simple one. Without the use of any 3rd party frameworks. Read on to find out!

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Requirements

Section B
The Library

Section C
Usage Example

Extra
Download & More

Closing
What’s Next?

 

 

SECTION A
THE REQUIREMENTS

Before we get started with the library and usage example, please make sure the GD Extension is enabled on your server. If not, this script will not be able to draw the captcha images properly.

GD EXTENSION MUST BE ENABLED

To check if you have the GD extension enabled on your web server, all you need is a quick check by creating a simple script with the phpinfo function.

check.php

If the GD extension is not enabled, simply edit the php.ini file and do a search for “extension”. In most cases, you only need to remove the semi-colon in front to enable the extension. If not, simply add another line in the under the extensions section:

php.ini
extension=gd2


 

SECTION B
THE LIBRARY

Now that we have the basic requirements out of the way, let us take a closer look at the Captcha library that will drive this entire project.

PHP SCRIPT

captcha.php

THE QUICK SUMMARY

Yep, one script is all you need to rule them all. It may look like a bunch of complicated code at first, but there are only 3 functions here – Each corresponding to a step on how to implement it in your project.

FunctionDescription
prime()The first step, which will create a random alphanumeric captcha string and put it into $_SESSION['captcha']. The default is 8 characters, and if you want a longer captcha string, simply pass in a bigger $length when calling this function.
draw()The second step, which generates the captcha image. As usual, you can control the width, height, font to use, and the font size – Please do remember to change the font path.
verify()The last step, verifies the given input – Simply matches it against $_SESSION['captcha'] and returns a true/false.

Finally, there are some extra bits at the bottom of the script to start the session and create the captcha object. You can remove these if you want, and manually do it yourself in your own project.


 

SECTION C
USAGE EXAMPLE

Now for an example of how to put the simple captcha library into actual use.

STEP 1) CREATE A FORM

1-form.php
prime();
// DRAW YOUR HTML FORM ?>


  
    
      PHP Captcha Demo
    

Nothing too complicated with this step:

  • Include the captcha script right at the top, and it will automatically start the session plus create a captcha object.
  • Call the prime function to generate a random captcha string into the session.
  • Create your HTML form as usual, but add a captcha field and an image pointing to a PHP file that will generate the captcha image.

STEP 2) THE CAPTCHA IMAGE

2-image.php
draw();

This is probably the easiest step… Just create a PHP file and use the captcha library to generate the image.

STEP 3) VERIFICATION

THE JAVASCRIPT

3-form.js
function process() {
  // Append data
  var data = new FormData();
  data.append("name", document.getElementById("name").value);
  data.append("email", document.getElementById("email").value);
  data.append("captcha", document.getElementById("captcha").value);

  // Init AJAX
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "3-verify.php", true);

  // When the process is complete
  // JSON decode the server response
  xhr.onload = function () {
    // console.log(this.response);
    var res = JSON.parse(this.response);
    if (res.status) {
      // ALL OK
      // Redirect user to thank you page or something
      // window.location.href = "thank-you.html";
      alert("OK");
    } else {
      // ERROR
      alert(res.message);
      // THIS WILL REFRESH THE CAPTCHA IF YOU WANT
      var cimg = document.getElementById("captcha-img");
      cimg.src = "2-image.php?" + new Date().getTime();
      document.getElementById("captcha").value = "";
    }
  };

  // Send
  xhr.send(data);
  return false;
}

Next, we need to handle the form submission. Here is a dummy Javascript that will grab all the form data – Inclusive of the captcha challenge, and post it to the server via AJAX.

SERVER-SIDE SCRIPT

3-verify.php
verify($_POST['captcha']);

// DO YOUR PROCESSING HERE
if ($verified) {
  // DO SOMETHING
  // REGISTER USER TO NEWSLETTER OR SOMETHING
  // RESPONSE
  unset ($_SESSION['captcha']);
  echo json_encode([
    "status" => 1,
    "message" => "OK"
  ]);
}

// INVALID CAPTCHA
else {
  // CREATE A NEW CAPTCHA IF YOU WANT
  $libCap->prime();
  echo json_encode([
    "status" => 0,
    "message" => "Invalid captcha"
  ]);
}

Finally on the server-side, all we need to do is to match the posted captcha string against the one in the session. If the challenge is successful, proceed with the processing as usual. If not, throw an error message back to the client-side, and ask to re-enter the captcha.


 

EXTRA
DOWNLOAD & MORE

That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.

GOOGLE RECAPTCHA

Want to save some system resources? Check out Google Recaptcha instead (it’s free).

3 Steps Simple PHP Contact Form With Recaptcha

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
  

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better fight spam in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post 3 Steps Simple Php Captcha Script (Free Download) appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

3 Steps Simple PHP Captcha Script (Free Download)

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×