PHP 7 Captcha Tutorial – Create Captcha in PHP Contact Form

Last updated on by Digamber
This tutorial explains about PHP Captcha, and we will learn how to create a PHP Captcha Script using the GD library, also look at how to validate the captcha with server-side PHP. Finally, we will also learn how to implement the captcha in the contact form.

The Internet is a place that is full of hackers and scammers, and hackers create malicious scripts to get access to your application. SQL injection, XSS attack, Bulk spam mails may bring tons of trouble for you.

Spam can enhance the server load and put your web application down, which leads to the unavailability of your web application. It directly affects site users or customers. In return, it impacts on your online business.

PHP Captcha Tutorial

Captcha is the best solution for this curse. It protects from unwanted access and spam bots. It prevents bots from sending useless data through the contact form in php.

CAPTCHA is a randomly generated code. It is produced in run time. It can be seen in various forms. For instance, here are the common types of Captcha:

  • Graphical (image)
  • Text
  • Audio

The captcha code is a random number, which needs to be filled by the user. Validation makes sure whether a real human enters the value, basically a bot faces a problem in filling the captcha code. This way, it prevents spam.

PHP Captcha with Contact Form Example

This is one of the easiest and a simple PHP CAPTCHA Script example implemented with PHP form. I have developed this project to give you the basic idea of how to get started with captcha to protect spam.

The project structure below can give you the ide of the thought process we are going to put in to stop spam using our free PHP captcha script.

We have a basic contact form with the name and email values that we will get from the site visitors. We have set up a captcha field inside the form layout. The captcha is required and has the validation implemented on it. It will be triggered when the user submits the form.

\-- php-captcha
  |-- config
      |--- database.php
  |-- assets
      |--- css
         |--- style.css
  |-- scripts
      |--- captcha.php
      |--- contact_form.php
  |-- index.php

HTML Contact Form with Captcha

Created a contact form using HTML and CSS with two Captcha fields in one field generate Captcha image in other field enter the value from captcha image to pass the validation.

<form action="" name="contactForm" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" id="name">
    </div>

    <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" name="email" id="email">
    </div>

    <div class="row">
        <div class="form-group col-6">
            <label>Enter Captcha</label>
            <input type="text" class="form-control" name="captcha" id="captcha">
        </div>
        <div class="form-group col-6">
            <label>Captcha Code</label>
            <img src="scripts/captcha.php" alt="PHP Captcha">
        </div>
    </div>

    <input type="submit" name="send" value="Send" class="btn btn-dark btn-block">
</form>

To add custom styling in the form use the following CSS.

.container {
    max-width: 500px;
    margin: 50px auto;
    text-align: left;
    font-family: sans-serif;
}

form {
    border: 1px solid #1A33FF;
    background: #ecf5fc;
    padding: 40px 50px 45px;
}

.form-control:focus {
    border-color: #000;
    box-shadow: none;
}

label {
    font-weight: 600;
}

.error {
    color: red;
    font-weight: 400;
    display: block;
    padding: 6px 0;
    font-size: 14px;
}

.form-control.error {
    border-color: red;
    padding: .375rem .75rem;
}

Create PHP Captcha with GD Library

Set captcha code in the PHP session. Generate a random number with 6 characters. This will be out security code. Create a basic captcha using the GD library built-in functions. This code will generate the captcha image.

<?php
  session_start();

  // Generate captcha code
  $random_num    = md5(random_bytes(64));
  $captcha_code  = substr($random_num, 0, 6);

  // Assign captcha in session
  $_SESSION['CAPTCHA_CODE'] = $captcha_code;

  // Create captcha image
  $layer = imagecreatetruecolor(168, 37);
  $captcha_bg = imagecolorallocate($layer, 247, 174, 71);
  imagefill($layer, 0, 0, $captcha_bg);
  $captcha_text_color = imagecolorallocate($layer, 0, 0, 0);
  imagestring($layer, 5, 55, 10, $captcha_code, $captcha_text_color);
  header("Content-type: image/jpeg");
  imagejpeg($layer);

?>

You can also create the advance captcha with customizable code length, character sets, and Unicode support, you can also customize captcha font using TTF font. Further features like image distortion, random lines, noise, alphanumeric captcha characters.

Add CAPTCHA to Contact Form

Add captcha with the contact form, and we get the captcha code from the session that we declared earlier. We have not validated the form, but we validated the captcha. When there is no captcha entered, the user will be notified with the required captcha message. When the user entered the wrong captcha user will also be alerted with a message.

<?php
    session_start();
    
    if(!empty($_POST["send"])) {
      $name = $_POST["name"];
      $email = $_POST["email"];
      $captcha = $_POST["captcha"];

      $captchaUser = filter_var($_POST["captcha"], FILTER_SANITIZE_STRING);

      if(empty($captcha)) {
        $captchaError = array(
          "status" => "alert-danger",
          "message" => "Please enter the captcha."
        );
      }
      else if($_SESSION['CAPTCHA_CODE'] == $captchaUser){
        $captchaError = array(
          "status" => "alert-success",
          "message" => "Your form has been submitted successfuly."
        );
      } else {
        $captchaError = array(
          "status" => "alert-danger",
          "message" => "Captcha is invalid."
        );
      }
    }  
?>

Include the contact_form.php in the index.php file to bind the captcha with contact form.

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>PHP Contact Form with Captcha</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/css/style.css">
</head>

<body>

  <div class="container mt-5">

    <?php include('scripts/contact_form.php'); ?>

    <!-- Captcha error message -->
    <?php if(!empty($captchaError)) {?>
      <div class="form-group col-12 text-center">
        <div class="alert text-center <?php echo $captchaError['status']; ?>">
          <?php echo $captchaError['message']; ?>
        </div>
      </div>
    <?php }?>

    <!-- Contact form -->
    <form action="" name="contactForm" method="post" enctype="multipart/form-data">
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" id="name">
      </div>

      <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" name="email" id="email">
      </div>

      <div class="row">
        <div class="form-group col-6">
          <label>Enter Captcha</label>
          <input type="text" class="form-control" name="captcha" id="captcha">
        </div>
        <div class="form-group col-6">
          <label>Captcha Code</label>
          <img src="scripts/captcha.php" alt="PHP Captcha">
        </div>
      </div>

      <input type="submit" name="send" value="Send" class="btn btn-dark btn-block">
    </form>
  </div>
</body>

</html>

Conclusion

In this tutorial, we successfully created a simple Captcha in PHP from scratch and implemented it with the PHP contact form. You can get the full code of this tutorial on GitHub.