etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

PHP Contact Form with CAPTCHA and Validation

In this article, you will learn how to create a contact form with CAPTCHA and validation using PHP Script.

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 block spammers that automatically sign up 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.





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.
PHP code to generate captcha and add in contact form with validation



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 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 stored session. Whenever the page reloads, it generates a new, challenging captcha image. Sometimes, the user faces trouble in 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 detail
PHP 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




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple pagination in PHP with MySQL
-----------------
How to generate QR Code in PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
To check whether a year is a leap year or not in php
-----------------
Php file based authentication
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
PHP Secure User Registration with Login/logout
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to print specific part of a web page in javascript
-----------------
Detect Mobile Devices in PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Google Street View API Example
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
PHP Programming Error Types
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
PHP Getting Document of Remote Address
-----------------
How to display PDF file in web page from Database in PHP
-----------------
File Upload Validation in PHP
-----------------
PHP FTP Connection and File Handling
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.