How to create contact form with captcha validation and send mail in PHP

A contact form is usually developed for the website users to be able to send their queries to the website admin. This topic is about developing a contact form with captcha validation and sending email after contact form is submitted.

You might be interested in below topics as well:

  1. How to send mail using PHP PEAR mail with SMTP authentication
  2. How to send mail using mail() function in PHP with example
  3. How to send mail from localhost using Gmail SMTP server in PHP

I will create a simple form for the user with few input fields (Name, Email, Message etc.) and a captcha. An email with details submitted by the user will be sent to the website admin. Below is the contact form:

PHP Contact form with captcha verification and send email

Below are the folders and files I have for this application:

Create a Contact Form in php with captcha

I have created a folder named 'contact' under 'xampp/htdocs' as I am using XAMPP. If you are using WAMP, create 'contact' folder under 'www'.

Folder 'css' - My custom stylesheet is in this folder
Folder 'js' - In this folder I have my custom JavaScript file
index.php is my main program for contact form as well as PHP code to process form inputs.
captcha.php is the php code written to generate captcha code.

Let us discuss each step in detail.

Step1 - Create a contact form (index.php)

Our contact form will have Name, Email, Phone, Message and an input to enter captcha code. There will be some validation for each field. Like, captcha code has to match with the one displayed. Additional validation for email id, it has to be a valid email id format. Let's see the code below:

Captcha is displayed as image here. See in line 38, an <img> element is added with source as captcha.php. We will discuss captcha.php in next step. There is a refresh button next to it and a JavaScript function getCaptcha() is called to refresh the captcha. getCaptcha() function calls captcha.php as image source so that a new captchae is generated. This function is written in captcha.js file in js folder. Take a look at the code:


Step2 - Develop a PHP program to generate captcha image(captcha.php)

In captcha.php we will write PHP code to generate random captcha every time captcha.php is called. captcha.php creates a dynamic image with some random alphanumeric string consisting of 5 characters. Let us look at the code:


This program creates a GD image instance with a fixed dimension. It uses a backgound color, a text color and draws 5 randomly chosen characters in it. Then it converts it to a PNG image. Also, it forms a string using those 5 characters and assigns the string in a session variable. So, the code displayed in the image is the same code which is stored in the session variable. Let us look into code in detail.

Line 3 - a GD image instance with specified dimension is created.
Line 4 - a set of characters (letter A-Z and digit 0-9) is defined. 5 randomly chosen characters from this set will be used in the captcha image. If you want lowercase letter to be included you can add a-z in this string.
Line 6 - a background color is chosen which is black in this case.
Line 7 - it fills the image with this background.
Line 8 - a text color which is white in this case, is defined.
Line 9 - a PHP session is started.
Line 11 - $code is initialized, this will contain the captcha.
Line 12 - 17, a loop is used five times to pick a character from $data string and drawn in the image. It shuffles the characters in $data using str_shuffle() and then it takes the first character in $char. $code is formed by concatenating each characters chosen this way. imagechar() function draws the character in the image instance. It has 5 parameters - image resource ($image), font size (5), x position ($x), y position (random number), char to print ($char) and textcolor ($textcolor). After this loop is finished, we have a 5 characters value stored in the $code variable and all these 5 characters are drawn in the image resource in the memory.
Line 19 - $code (string of 5 chars) is stored in a session variable.
Line 20, 21 - converts the image into a PNG image
Line 22 - clear the memory image resource occupied, if any.

Step3 - Write PHP code to process form inputs and send mail (index.php)

When the form is submitted, we need to write php code to process those values entered by the user and send a mail. We will do some validation for input values. Also, there will be validation for correct email id format and phone number which is 10 digits in this case. If any validation fails, it will give message and will not proceed to process the form. Let us see the code:

If any validation fails $error is set as true. We must verify the captcha code entered by the user is same as stored in the session variable $_SESSION['code'].

If all validations are successful, it formats the mail and sends a mail to a specified email id as given by the website.

mail() function in line uses 4 parameters.

  1. To - To email id, whom the query/message of the user to be sent to.
  2. Subject - Subject of the email
  3. Mail Body - Body of the mail as formatted with message entered by the user in the form
  4. Header - Header of the message which we have formed it here in the code as $headers. Usually it contains the document type, from email id, cc and bcc.

I have given index.php and custom stylesheet here. You can also download the code from download section later in this topic.


Below is the stylesheet I used.


Test the Application

To test it, just open localhost/contact in your browser, contact form will be displayed as below:

make contact form and send email in PHP

Check that captcha is displayed and when you click on refresh button, new code is generated. Now to test the contact form, you need to set up mail server so that contact form will be sent to the email id as needed. You can read below topics about sending mail in PHP:

  1. How to send mail with SMTP authentication using PEAR mail in PHP
  2. How to send mail using mail() function in PHP
  3. How to send mail using Gmail in PHP

When I tested it using Gmail from my localhost, I got the email in my Gmail inbox as given below:

Contact form in PHP with captcha

Below is the mail:

contact us page

develop a contact form in phpImportant Note

PHP mail() function could be disabled in servers because of security. PEAR Mail or any other mail sending option using SMTP authentication is a better way to send mail in PHP.

php contact form send email codeDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

Create a Simple Captcha Script Using PHPConclusion

Contact form is used in almost all websites, so it is a very common form. Only the mail part of it needs to be setup. In fact, you can setup your localhost to send mail using Gmail account. I have already mentioned the topics you can read about sending mails in PHP. Hope it will be useful for you.