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 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, forum and so on. So, the CAPTCHA basically distinguish human from automated programs. It makes a challenge for 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 session.
  • Create HTML form, add captcha image and an input box to enter captcha.
  • Match the entered captcha word with stored session.
PHP code to generate captcha and add in contact form with validation



Here, we have written a PHP script to generate 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 a 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 on 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 reload, 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 forum, comment box, blogs, registration form and so on.





Related Articles

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
PHP Connection and File Handling on FTP Server
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
PHP7.3 New Features, Functions and Deprecated Functions




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


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 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

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


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