PHP Contact Form with CAPTCHA and Validation
In this article, you will learn how to create an HTML contact form with CAPTCHA validation using the PHP programming language.
CAPTCHA is abbreviated as "Completely Automated Public Turing test to tell Computers and Humans Apart". It is a random series of letters represented as a distorted image. It is a type of challenge-response framework intended to separate humans from robotic software programs. It protects us from bots, which automatically submit forms with unwanted content. This basically blocks spammers that automatically sign up for hundreds of free accounts, or make use of the comment section, blogs, forums, and so on. So, the CAPTCHA basically distinguishes humans from automated programs. It makes it a challenge for a human before submitting the form.
PHP contact form with captcha
Steps to generate and add Captcha in a form
These are the following steps taken-
- Generate Captcha image and stores the word in the session.
- Create an HTML form, add a captcha image and an input box to enter the captcha.
- Match the entered captcha word with the stored session.
Here, we have written a PHP script to generate a CAPTCHA image. For this, we have used the following PHP predefined image functions.
imagecreatetruecolor()- It is used to create a true-color image.
imagecolorallocate()- It allocates a color for an image.
imagefilledrectangle()- It is used to draw a filled rectangle.
imageline()- It is used to draw a line.
imagesetpixel()- It sets a single pixel.
imagestring()- It draws a string horizontally.
imagepng()- It returns a PNG image.
generate_captcha.php
In the given PHP code, we have generated an image for the captcha and saved the captcha code in the PHP session.
<?php
$image = imagecreatetruecolor(200, 50);
//set line color and number of lines in background
$set_linecolor = imagecolorallocate($image, 101, 62, 8);
$no_of_lines = rand(3,6);
//image background
$set_bgcolor = imagecolorallocate($image, 255, 212, 178);
imagefilledrectangle($image,0,0,200,50,$set_bgcolor);
// draw lines in background
for($i=0; $i<$no_of_lines; $i++)
{
imageline($image,0,rand()%50,250,rand()%50,$set_linecolor);
}
$set_pixel = imagecolorallocate($image, 0,0,255);
for($i=0;$i<500;$i++)
{
imagesetpixel($image,rand()%200,rand()%50,$set_pixel);
}
// Set captcha letters
$range = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$length = strlen($range);
$captcha = $range[rand(0, $length-1)];
$word = '';
$text_color = imagecolorallocate($image, 0,0,0);
$cap_length = 7; // No. of character in image
for ($i = 0; $i< $cap_length; $i++)
{
$captcha = $range[rand(0, $length-1)];
imagestring($image, 15, 5+($i*30), 20, $captcha, $text_color);
$word.= $captcha;
}
// store the captcha letters in session
$_SESSION['captcha_word'] = $word;
imagepng($image, "captcha.png");
?>
index.php
Here is the main file that we will call in the browser. This file includes the above file to generate a captcha image. We store the generated captcha letters in session. So that we can match the captcha letters entered by the user with the stored session. Whenever the page reloads, it generates a new, challenging captcha image. Sometimes, the user faces trouble detecting the captcha letters. For this, we have added a button to refresh this with a new one.
<?php
session_start();
// Check for valid captcha
if($_SESSION['captcha_word']==$_POST["input"])
{
echo "Thanks for validation! You can proceed now.";
}
else
{
echo "Please enter valid captcha.";
}
unset($_SESSION['captcha_word']);
include("generate_captcha.php");
?>
<html>
<head>
<title>Form Captcha Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
</head>
<body>
<div>
<h1>Fill the form and validate the captcha</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<div class="container">
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="1" name="comment"></textarea>
</div>
<div class="form-group">
<img src="captcha.png">
<input type="text" name="input"/>
<input type="submit" value="submit" name="submit"/>
</div>
</div>
</form>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="submit" value="refresh captcha">
</form>
</div>
</body>
</html>
So, this is how we generate and validate the CAPTCHA in a contact form. Similarly, we can implement this script in the forum, comment box, blogs, registration form, and so on.
Related Articles
PHP Set a cookie to store login detailPHP code to send email using SMTP
PHP differentiate between fgets, fgetss and fgetcsv
PHP ftp server connection and file handling
Sending form data to an email using PHP
PHP Secure User Registration with Login/logout
PHP user registration & login/ logout with secure password encryption
How to add google reCAPTCHA v2 in registration form using PHP
Simple pagination in PHP
Simple PHP File Cache
PHP7.3 New Features, Functions and Deprecated Functions
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Complete HTML Form Validation in PHP
Submit a form data without page refresh using PHP, Ajax and Javascript
PHP Server Side Form Validation
How to send emojis in email subject and body using PHP
File Upload Validation in PHP