Reader Level:
ARTICLE

How to Create Captcha in PHP

Posted by Vinod Kumar Articles | PHP January 30, 2013
In this article I explain how to create a Captcha in PHP.
  • 0
  • 0
  • 2816

Introduction

In this article, I describe how to create a Captcha in PHP. Such as when we submit a form a Captcha is often used. A Captcha is an image that is like a verification code. I am using a simple Captcha image without any other custom font to create an image or code. The Captcha code is stored in a session variable. We are using the session variable "cap_code" for the code the user entered and compare it to the session variable. A Captcha is a smartly blurred image and a Captcha code avoid spam and auto submissions. In this article, I am using "css" and "jquery" for additional functionality.

Captcha-in-php.jpg

The $_SESSION[variable] creates the original Captcha code and $_POST['captcha'] - Captcha create a code and user enter the code in text box.

Example

This file is "captcha.php":

<?php

//session start

session start();

// calculates the MD5 hash of a string

$Str = md5(microtime());

//substr is a string function

$Str = substr($Str, 0, 6);

      //cap_code is a session variable

$_SESSION['cap_code'] = $Str;

         //cap_bg is image

$newImage = imagecreatefromjpeg("cap_bg.jpg");

$txtColor = imagecolorallocate($newImage, 0, 0, 0);

imagestring($newImage, 5, 5, 5, $Str, $txtColor);

header("Content-type: image/jpeg");

imagejpeg($newImage);

?>

Simply create a HTML form and include the jQuery code in the head section jQuery uses for validaion. I am using "CSS/JQuery"; I used that just for an extra enhancement.

<?php

//session start here

session_start();

$cap = 'notEq';//this variable use for message

if ($_SERVER['REQUEST_METHOD'] == 'POST')

{

if ($_POST['captcha'] == $_SESSION['cap_code'])

{

// Code is Correct. Do something here!

$cap = 'Eq';

}

else

{

// Code is wrong. Take other action

$cap = '';

}

}

?>

<html>

<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $('#submit').click(function () {

            var name = $('#name').val();

            var msg = $('#msg').val();

            var captcha = $('#captcha').val();

            if (name.length == 0) {

                $('#name').addClass('error');

            }

            else {

                $('#name').removeClass('error');

            }

            if (msg.length == 0) {

                $('#msg').addClass('error');

            }

            else {

                $('#msg').removeClass('error');

            }

            if (captcha.length == 0) {

                $('#captcha').addClass('error');

            }

            else {

                $('#captcha').removeClass('error');

            }

            if (name.length != 0 && msg.length != 0 && captcha.length != 0) {

                return true;

            }

            return false;

        });

        var capch = '<?php echo $cap; ?>';

        if (capch != 'notEq') {

            if (capch == 'Eq') {

                $('.cap_status').html("Your form is successfull submited ").fadeIn('slow').delay(3000).fadeOut('slow');

            }

            else {

                $('.cap_status').html("Verification Code Wrong!").addClass('cap_status_error').fadeIn('slow');

            }

        }

    });

</script>

 

<style>

body{

width: 600px; margin: 0 auto; padding: 0;

}

.error

{

border: 1px solid red;

}

.cap_status

{

width: 350px; padding: 10px; font: 14px arial; color: #fff; background-color: #10853f; display: none;

}

.cap_status_error

{

background-color: #bd0808;

}

</style>

</head>

<body bgcolor="#FEFDE2">

<form action="" method="post">

<label>Name:</label><br/>

<input type="text" name="name" id="name"/><br>

<label>Message:</label><br/>

<textarea name="msg" id="msg" rows="3" cols="16"></textarea><br>

<label>Enter The Code

<img src='captcha.php' /></label><br>

<input type="text" name="captcha" id="captcha" />

 

<input type="submit" value="Submit" id="submit"/>

</form>

<div class="cap_status"></div>

</body>

</html>

Output

When we enter the wrong verification code in the text box:

Captcha-in-php1.jpg

Then this error is shown; this error is created in jQuery:

Captcha-in-php2.jpg

When we enter the correct verification code in the text box:

Captcha-in-php3.jpg

Then this message is shown:

 Captcha-in-php4jpg.jpg

COMMENT USING

Trending up