Skip to main content

PHP Captcha

When allowing users to enter data into our website, we need to check whether the data is entered by the human. Otherwise, people will use robots to push the bulk of unwanted data into the website. It will cause a lot of problems like XSS attack or increase server load to down the website. CAPTCHA is one of the methods to prevent robots from entering data. CAPTCHA can be text-based, audio-based or graphics-based random code generated dynamically. On submitting user input, this code will be mandatory which will help to capture robot not entering captcha code.
In this tutorial, I have a contact form to get the user input. This form includes name, email, message subject and message body fields to get messages from the user. I have created a random captcha code and stored it in a session. This captcha code will be displayed in the contact form which should be entered by the user to submit their messages. I have the server side validation to check whether the code is not empty and valid.

PHP code to Create CAPTCHA

In this section, I cover the PHP code for creating CAPTCHA code to be stored in a session variable. I start the session to store the captcha which is dynamically created using the PHP rand() function. I have created an image target layer and write the random code. This JPEG captcha image will be shown in the contact form. The image creation and resizing code are shown as below.
<?php
session_start();
$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$target_layer = imagecreatetruecolor(70,30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
imagefill($target_layer,0,0,$captcha_background);
$captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/jpeg");
imagejpeg($target_layer);
?>

Add captcha into HTML Contact Form

This code shows the HTML contact form with the CAPTCHA code.
<html>
<head>
<title>Contact Us Form</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form name="frmContact" method="post" action="">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="1" width="500" align="center">
<tr class="tableheader">
<td colspan="2">Enter Contact Information</td>
</tr>
<tr class="tablerow">
<td>Name<br/><input type="text" name="userName"></td>
<td>Email<br/><input type="text" name="userEmail"></td>
</tr>
<tr class="tablerow">
<td colspan="2">Subject<br/><input type="text" name="subject" size="73"></td>
</tr>
<tr class="tablerow">
<td colspan="2">Content<br/><textarea name="content" cols="60" rows="6"></textarea></td>
</tr>
<tr class="tablerow">
<td colspan="2">Captcha Code<br/><input name="captcha_code" type="text"><br>
<img src="captcha_code.php" /></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>

Compare Captcha Code

On form submit, we should verify the captcha code, by comparing it with the corresponding $_SESSION variable. If match found, then, the user is recognized as human and the user information will be processed in the PHP file. Otherwise, Captcha validation error message will be displayed to the user. The code for validating the captcha is,
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "test", "blog_samples") or die("Connection Error: " . mysqli_error($conn));

if (count($_POST) > 0) {
    if ($_POST["captcha_code"] == $_SESSION["captcha_code"]) {
        $success_message = "Your message received successfully";
        mysqli_query($conn, "INSERT INTO tblcontact (user_name, user_email,subject,content) VALUES ('" . $_POST['userName'] . "', '" . $_POST['userEmail'] . "','" . $_POST['subject'] . "','" . $_POST['content'] . "')");
    } else {
        $error_message = "Incorrect Captcha Code";
    }
}
?>

Output

Following screenshot shows the random captcha code in the contact form.

Comments

Post a Comment

Popular posts from this blog

Build chatbot with node js and react js

User Experience is given a lot of attention while building any application these days. More and more brands are leveraging chatbots to service their customers, market their brand, and even sell their products. There are a lot of awesome tools out there which helps in building an intelligent bot very easily like Google’s DialogFlow, Amazon Lex, etc, most of which implement their own Natural Language Processing (NLP) logic. However, in some cases, we don’t really need an intelligent bot. Whenever we have a small application having a limited set of options to choose from, it’s not really necessary to use NLP based tools like Google’s DialogFlow. You need to integrate with them (which is pretty easy though), and you need to make a network call to get the results. Instead, you would want to define your rules locally in those cases. Here we will build a simple chatbot using React Simple Chatbot library and add it to our pizza-builder app using which we can build ou...

PHP Image Upload with Size Type Dimension Validation

File upload feature requires basic validations to  make clean and hygienic  the user input. There is a huge chance of exploiting a file upload option with malicious intent. Improper implementation of a file upload input increases security vulnerability. We need to validate the uploaded files before saving them on the server to reduce the vulnerability. I have created a HTML form and provided an option to upload files. When the form is submitted, the file binaries are sent to the PHP and validated in the server side. I have checked if the uploaded file is an image and I have specified the allowed image extension, size and dimension based on which the validation is taking place. After all these validations have passed, the image file is saved in the target location as specified. The server-side image file validation takes place in the following aspects. If the file is not empty. If the file extension is one of .jpg, .png, .jpeg. If the file size is le...

Arrays In PHP

Have you ever heard about Array.A n Array is a   PHP datatype  used to store a group of data into a variable. Each array item is stored as a key and value pair. Arrays are classified as “indexed array” and “associative array” based on the key specification. The Indexed array has default index starts with ‘0’ and the associative array contains the user-defined key index. The array can also be classified as “one-dimensional array” and “multi-dimensional array” based on the level of the array index. In this tutorial, we are going to see some of the important array functions in PHP. PHP Array Functions In this section, we are going to see some of the widely used PHP array functions. I explain the purpose of the array functions, the parameter it requires and the default values of the parameter. This section includes small and simple PHP code snippets to explain the usage of each array function.  range(start, end) PHP  range()  fu...