how to implement custom captcha code in php Script?

Today, We want to share with you captcha code in php.In this post we will show you Build Your Own CAPTCHA and Contact Form in PHP, hear for Creating custom captcha in PHP we will give you demo and example for implement.In this post, we will learn about how to implement custom captcha in php with an example.

captcha code in php

There are the Following The simple About custom captcha code in php Full Information With Example and source code.

As I will cover this Post with live Working example to develop A Simple PHP CAPTCHA Script, so the simple captcha code in php free download is used for this example is following below.

Step 1: Creating Database and Table

inquiry_form_captcha.sql

-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Feb 04, 2020 at 05:15 AM
-- Server version: 5.6.37
-- PHP Version: 7.1.23

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `inquiry_form_captcha`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_inquiry`
--

CREATE TABLE `tbl_inquiry` (
  `id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `user_email` varchar(255) NOT NULL,
  `subject` text NOT NULL,
  `Inquiry` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_inquiry`
--
ALTER TABLE `tbl_inquiry`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_inquiry`
--
ALTER TABLE `tbl_inquiry`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
COMMIT;

/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;

Step 2: Creating Landing page

index.php

<?php
use Pakainfo\Captcha;
use Pakainfo\inquiry;

require_once "./Model/Captcha.php";
$captcha = new Captcha();
if (count($_POST) > 0) {
    $userCaptcha = filter_var($_POST["captcha_code"], FILTER_SANITIZE_STRING);
    $isValidCaptcha = $captcha->validateCaptcha($userCaptcha);
    if ($isValidCaptcha) {
        
        $userName = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
        $userEmail = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
        $subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
        $Inquiry = filter_var($_POST["Inquiry"], FILTER_SANITIZE_STRING);
        
        require_once "./Model/inquiry.php";
        $inquiry = new inquiry();
        $insertId = $inquiry->addToinquirys($userName, $userEmail, $subject, $Inquiry);
        if (! empty($insertId)) {
            $success_message = "Your message received successfully";
        }
    } else {
        $error_message = "Incorrect Captcha Code";
    }
}
?>
<html>
<head>
<title>inquiry Form with PHP Captcha</title>
<link href="./assets/css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <h2>inquiry Form with PHP Captcha</h2>
    <form name="frminquiry" method="post" action="">
        <table border="0" cellpadding="10" cellspacing="1" width="100%"
            class="inquirey-table">
            <tr class="tablerow">
                <td width="50%">Name<br /> <input type="text"
                    name="userName" class="inquirey-input" required></td>
                <td width="50%">Email<br /> <input type="email"
                    name="userEmail" class="inquirey-input" required></td>
            </tr>
            <tr class="tablerow">
                <td colspan="2">Subject<br /> <input type="text"
                    name="subject" class="inquirey-input" required></td>
            </tr>
            <tr class="tablerow">
                <td colspan="2">Inquiry<br /> <textarea name="Inquiry"
                        class="inquirey-input" rows="5" required></textarea></td>
            </tr>
            <tr class="tablerow">
                <td>Captcha Code: <span id="error-captcha"
                    class="inquirey-error"><?php if(isset($error_message)) { echo $error_message; } ?></span>
                    <input name="captcha_code" type="text"
                    class="inquirey-input captcha-input">
                </td>
                <td><br /> <input type="submit" name="submit"
                    value="Submit" class="inquirey-btn"></td>
            </tr>
        </table>
<?php if(isset($success_message)) { ?>
<div class="inquirey-success"><?php echo $success_message; ?></div>
<?php } ?>
</form>
</body>
</html>

Step 3: Create a captcha Image Source File

captchaImageSource.php

<?php
namespace Pakainfo;

use Pakainfo\Captcha;

session_start();

require_once "./Model/Captcha.php";
$captcha = new Captcha();

$captcha_code = $captcha->getCaptchaCode(6);

$captcha->setSession('captcha_code', $captcha_code);

$imageData = $captcha->createCaptchaImage($captcha_code);

$captcha->renderCaptchaImage($imageData);

?>

Step 4: Create a PHP Captcha Model

Captcha.php

<?php
namespace Pakainfo;

class Captcha
{

    function getCaptchaCode($length)
    {
        $random_alpha = md5(random_bytes(64));
        $captcha_code = substr($random_alpha, 0, $length);
        return $captcha_code;
    }
    
    function setSession($key, $value) {
        $_SESSION["$key"] = $value;
    }
    
    function getSession($key) {
        @session_start();
        $value = "";
        if(!empty($key) && !empty($_SESSION["$key"]))
        {            
            $value = $_SESSION["$key"];
        }
        return $value;
    }

    function createCaptchaImage($captcha_code)
    {
        $target_layer = imagecreatetruecolor(72,28);
        $captcha_background = imagecolorallocate($target_layer, 204, 204, 204);
        imagefill($target_layer,0,0,$captcha_background);
        $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
        imagestring($target_layer, 5, 10, 5, $captcha_code, $captcha_text_color);
        
        return $target_layer;
    }

    function renderCaptchaImage($imageData)
    {
        header("Inquiry-type: image/jpeg");
        imagejpeg($imageData);
    }
    
    function validateCaptcha($formData) {
        $isValid = false;
        $capchaSessionData = $this-> getSession("captcha_code");
        
        if($capchaSessionData == $formData) 
        {
            $isValid = true;
        }
        return $isValid;
    }
}

Step 5: Create a PHP inquiry Model

inquiry.php

<?php
namespace Pakainfo;

use Pakainfo\DataSource;

class inquiry
{

    private $ds;

    function __construct()
    {
        require_once __DIR__ . './../lib/DataSource.php';
        $this->ds = new DataSource();
    }

    function addToinquirys($userName, $userEmail, $subject, $Inquiry)
    {
        $insertQuery = "INSERT INTO tbl_inquiry (user_name, user_email, subject, Inquiry) VALUES (?, ?, ?, ?)";
        
        $paramType = 'ssss';
        $paramValue = array(
            $userName,
            $userEmail,
            $subject,
            $Inquiry
        );
        $insertId = $this->ds->insert($insertQuery, $paramType, $paramValue);
        return $insertId;
    }
}

Step 6: Create a Data Source File

lib/DataSource.php

<?php
namespace Pakainfo;


class DataSource
{

    const HOST = 'localhost';

    const USERNAME = 'root';

    const PASSWORD = 'test';

    const DATABASENAME = 'inquiry_form_captcha';

    private $conn;


    function __construct()
    {
        $this->conn = $this->getConnection();
    }

    public function getConnection()
    {
        $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME);

        if (mysqli_connect_errno()) {
            trigger_error("Problem with connecting to database.");
        }

        $conn->set_charset("utf8");
        return $conn;
    }

    public function select($query, $paramType = "", $paramArray = array())
    {
        $stmt = $this->conn->prepare($query);

        if (! empty($paramType) && ! empty($paramArray)) {

            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }

        if (! empty($resultset)) {
            return $resultset;
        }
    }

    public function insert($query, $paramType, $paramArray)
    {
        $stmt = $this->conn->prepare($query);
        $this->bindQueryParams($stmt, $paramType, $paramArray);

        $stmt->execute();
        $insertId = $stmt->insert_id;
        return $insertId;
    }

    public function execute($query, $paramType = "", $paramArray = array())
    {
        $stmt = $this->conn->prepare($query);

        if (! empty($paramType) && ! empty($paramArray)) {
            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        $stmt->execute();
    }

    public function bindQueryParams($stmt, $paramType, $paramArray = array())
    {
        $paramValueReference[] = & $paramType;
        for ($i = 0; $i < count($paramArray); $i ++) {
            $paramValueReference[] = & $paramArray[$i];
        }
        call_user_func_array(array(
            $stmt,
            'bind_param'
        ), $paramValueReference);
    }

    public function getRecordCount($query, $paramType = "", $paramArray = array())
    {
        $stmt = $this->conn->prepare($query);
        if (! empty($paramType) && ! empty($paramArray)) {

            $this->bindQueryParams($stmt, $paramType, $paramArray);
        }
        $stmt->execute();
        $stmt->store_result();
        $recordCount = $stmt->num_rows;

        return $recordCount;
    }
}

step 7: Create a CSS File

style.css

body {
	font-family: arial;
    max-width: 610px;
    font-size: 0.95em;
    color: #232323;
}
.inquirey-error {
	color:#FF0000;
    font-size: 0.95em;
}
.inquirey-input {
    width: 100%;
    border-radius: 5px;
    border: #CCC 1px solid;
    padding: 12px;
    margin-top: 5px;
}
.inquirey-btn {
	    padding: 12px;
    border-radius: 5px;
    background: #232323;
    border: #284828 1px solid;
    color: #FFF;
    width: 100%;
    cursor: pointer;
    margin-top: 4px;
}
.inquirey-table {
    border-radius: 3px;
    padding: 10px;
    border: #E0E0E0 1px solid;
}
.inquirey-success {
    margin-top: 5px;
    color: #478347;
    background: #e2ead1;
    padding: 10px;
    border-radius: 5px;
}
.captcha-input {
	background: #FFF url(./../../captchaImageSource.php) repeat-y left center;
    padding-left: 85px;
}

I hope you get an idea about captcha code in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Read Also:  Laravel Add active class to Nav Menu System

About Pakainfo

I am Jaydeep Gondaliya, a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Pakainfo →

Leave a Reply

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