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

Create facebook messenger chatbot using PHP

Chatbots are the latest sensation in social media communication channels. These automated chat systems are especially build to receive vistiors on social media chats and provide basic information to the visitors about your business. This information could include event schedules, product information, latest deals, store offers and general information about the brand. Entrepreneurs and brand marketers employ chatbots to handle the bulk of chats queries. This way, a large number of queries could be easily handled with minimum costs. Chatbots help reduces the dependence on human customer service representatives (CSR). These chatbots vet out common queries so that the human CSR cold focus on queries that require processing of multiple information sources. Since chatbots steer all conversation toward a pre-set direction, it is easy and time-efficient to use these chatbots instead of human CSR. In this article, I will create a simple Facebook chatbot that could carry out an

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

Now About PHP Info

Have you ever heard about phpinfo(). Yes, this function is used to know about configuration details of PHP installed in our machine. Such detailed information returned by this phpinfo() includes platform information, PHP and server environment, HTTP header information, PHP core details like version and directives status, License information and etc. phpinfo() function has an optional argument. If this function is called with no argument, then will display all information. We can check it by executing the following code. <? php phpinfo (); ?> We can also request specific details to be displayed to the browser by passing available constants to this function. Following list shows such available options. INFO_GENERAL – This will return information about the platform, compiler, architecture, API and etc. INFO_CREDITS – This option provides a hyperlink which shows details about authors, documentation, QA and infrastructure team. INFO_CONFIGURATION – Disp