How to Create Captcha in PHP 8 Contact Form

Last Updated on by in PHP
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.

Create PHP Project

We must have either XAMPP or MAMP webserver set up and running in our development machine.

Get inside the htdocs folder, inside this folder you have to create a new php-demo folder.

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-demo
  |-- config
      |--- database.php
  |-- assets
      |--- css
         |--- style.css
  |-- scripts
      |--- captcha.php
      |--- contact_form.php
  |-- index.php

Create Database Connection

In order to establish connection between server and PHP application, make sure to config/ folder, create database.php file and the below code.

<?php

    $hostname = "localhost";
    $username = "phpdemo";
    $password = "";

    try {
        $connection = new PDO("mysql:host=$hostname;dbname=php_crud", $username, $password);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }

?>

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.

Create scripts/ folder, create contact_form.php file then put the following code in the file.

<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.

Create assets/css/ folder, create style.css file then put the following code in the file.

.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.

Create scripts/ folder, create captcha.php file and insert the given code in the file.

<?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.

Create scripts/ folder, create contact_form.php file and insert the given code in the file.

<?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>

View App on Browser

To see app in the action, ensure that you add and run the given URL on the browser.

http://localhost/php-demo/

Conclusion

In this tutorial, we successfully created a simple Captcha in PHP from scratch and implemented it with the PHP contact form.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.