Contact form using PHP, and AJAX with captcha validation | Bootstrap

The contact form is used to take data from the users. The main benefit of the contact form is to provide support and services to the website visitor.  In this tutorial, we will create a contact form in PHP and AJAX with captcha validation. As you know there are a lot of spammers on the internet. They can spam your email system. We use a captcha system to prevent all spam by contact form. A user cannot send an email without filling correct captcha. In this contact form, we will use bootstrap. Bootstrap is one of the famous framework. We can make a responsive HTML form or contact page using bootstrap. We will use ajax to create a smooth contact form in PHP. Ajax is used to create operations (CRUD) without page refreshing also we will use jquery. jQuery is one of the best JS framework. 

How to create a contact form in PHP and, AJAX with captcha validation – 

In web development, security plays an important role. The contact form should be secured and protected with captcha validation system. On the contact page, a user can send a message to the site owner. We will use HTML form and PHP mail() function to deliver contact email to the admin email id. 
First of all, we create a contact form using bootstrap.


<!DOCTYPE html>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Contact Us </title>
<link href="" rel="stylesheet">
<script src=""></script>
<link rel="stylesheet" href="">
<link href="style.css" rel="stylesheet">
<script src="contact_scripts.js"></script>
<div class="container">
	<div class="row">
		<div class="col-sm-2">
		<div class="col-sm-8">
			<div class="form-container">
    		<h2 class="title">Contact Us </h2>
              <p id="msg" class="text-danger"></p>
              <p id="success"></p>
    		  <div id="hide_form">
    		<div class="row">
    			<div class="col-sm-6">
    				<label class="label">Name </label>
    				 <input type="text" name="fname" id="fname" class="form-control" placeholder="What's your name?">
    				<div class="col-sm-6">
    				<label class="label">Email </label>
    				 <input type="email" name="email" id="email" class="form-control" placeholder="What's your email?">
    			<div class="col-sm-6">
    				<label class="label">Mobile</label>
    				 <input type="number" name="email" id="mobile" maxlength="10" class="form-control" placeholder="What's your mobile number?">
    			<div class="col-sm-6">
    				<label class="label">Service Category</label>
    				 <select name="category" id="category" class="form-control" required>
                 <option value="">Select Any </option>
                <option value="Tech Support">Tech Support</option>
                  <option value="Business Management">Business Management</option>
    				 	  <option value="Other">Other </option>
    		<div class="col-sm-12">
    			  <div class="form-group">
    			<label class="label">Message </label>
    			<textarea name="msg" id="msg" class="form-control"></textarea>
    	<div class="col-sm-2">
<div class="col-sm-4">
    				<label class="label"></label>
    				<span  style="float: right;">
    				 <img src="captchaimg.php" id="captcha"> <i class="fa fa-sync" aria-hidden="true" class=".refv" onClick="refreshCaptcha();"></i>
    			<div class="col-sm-4">
    				<label class="label"></label>
    				 <input type="text" name="captcha_val" id="captcha_val" class="form-control" placeholder="Enter Captcha">
    			<div class="col-sm-2">
    		<div class="col-sm-12">
    		  <div class="form-group text-center">
    			  <button class="btn btn-primary" id="sendnow">Send Message </button>
                  <div id="subloader"></div>
		<div class="col-sm-2">


In the code above, we created a contact form using bootstrap CSS classes. We linked bootstrap and jquery classes as well as extra CSS and JS files. 
We create unique id names for all fields like – name, email, mobile, message, and for send button "sendnow". 
In the contact form, the user fills all the details like – full name, email, and message, and clicks on send message button. After clicking send message button a jquery function works using the send message button id "sendnow" and the AJAX code executes. 
Let’s create a JS file – 


$("#sendnow").click(function() {
        var email = $('#email').val().trim();   
          var fname = $('#fname').val().trim();
         var category = $('#category').val().trim();
         var mobile = $('#mobile').val().trim();
        var captcha_val=$('#captcha_val').val().trim(); 
         var msg =$('textarea[name="msg"]').val();
        url: "contact_action.php",
        data:{fname: fname, category: category, mobile: mobile, msg: msg, email: email, captcha_val: captcha_val },
        beforeSend: function() {
              $('#subloader').html('<img src="loader.gif" height="100">');
           success: function(data){

         var obj = JSON.parse(data);
  var status=obj.status ; 
    $('#success').html('Thank you ' + fname + ' ! Your message has been sent . We will contcat you soon as possible.. ');

 function refreshCaptcha() {

We created code for ajax in the file above. First of all, we save field data by field id in different variables. After that, we send data to the contact_action.php file using AJAX. 
When a user clicks send message button the ajax response sends all the field data to the PHP action file the PHP file gets executed and the page never gets refreshed. 
Let’s create a contact_action.php file. 


<?php session_start();
 $error= array();
            $error[] = 'Please enter Full Name using 3 charaters atleast.';
            if(!preg_match("/^[a-zA-Z\s]+$/", $fname)){
            $error[] = 'Full Name:Characters Only (No digits or special charaters) ';
            $error[] = 'Full Name: Max length 20 Characters Not allowed';
         if($email ==''){
            $error[] = 'Please enter email';

            if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)){
            $error[] = 'Enter Valid email id';
            $error[] = 'Mobile: Please enter 10 digits mobile number without country code';
            $error[] = 'Please select service category';
            $error[] = 'Please enter your message';
    if($captcha_val ==''){
            $error[] = 'Please enter captcha';
              if ($_SESSION['captcha'] != $captcha_val)
         $error[]='Invalid captcha'; 



         $i='<i class="fa fa-warning"></i>';
        foreach($error as $err)
        $erro[]=$i.' '.$err;  
        $error_str=implode('<br>', $erro); 
            $FromName='Techno Smarter';
$credits="All rights are reserved | ".$FromName; 
$headers  = "MIME-Version: 1.0\n";
     $headers .= "Content-type: text/html; charset=iso-8859-1\n";
     $headers .= "From: ".$FromName." <".$FromEmail.">\n";
      $headers .= "Reply-To: ".$ReplyTo."\n";
      $headers .= "X-Sender: <".$FromEmail.">\n";
       $headers .= "X-Mailer: PHP\n"; 
       $headers .= "X-Priority: 1\n"; 
       $headers .= "Return-Path: <".$FromEmail.">\n"; 
         $subject="You have received a contact message from  ".$FromName; 
     $msg=$message='Name:- '.$fname.'<br>Email:- ' .$email.'<br> Mobile Number:- '.$mobile.'<br> Service Category:- '.$category.'<br> Message:- '.$msg;
  if(mail($to_email, $subject, $msg, $headers,'-f'.$FromEmail) ){

    else {
       $error_str="Server failed to send email , Please try again ...";
        $response = array(
        'errors' =>  $error_str,
        'status' => $last_status
echo json_encode($response);


Validations are more important in the contact form. In the code above, we created many validations for name, email, message, mobile number, and category. 
You can change the maximum and minimum length in-validations. 
After that, we used the mail() function. The mail() function is used to send emails. You have to set these details here – 

$FromName='Techno Smarter'; // Your website name 
$FromEmail='';  // your website official email like –
 $to_email='';  //  Your email where you want to receive all the contact emails. 

Please make sure, all of these details are correct. 
After that, we encode JSON data and parse it into the ajax success function and display the success message. 
As you know, we are creating a contact form with captcha validation system. We display an image with unique numbers. Let's create an image with unique text. We already provided a captcha image link on the contact page. 
Let’s create the captcha image file. 

<?php session_start();
 $_SESSION['captcha'] = $str;

In the code above, we started the session because we will match the entered value and session value to validate the captcha on the contact page. 
We use rand() function to write the random number on the image. As you can see we created a function captcha and included a captcha.php file. 
The captcha() a user-defined function is created in the captcha.php file. 


function captcha($string) 
 header("Content-type: image/jpeg");
    $imgPath = 'background.jpg';
    $image = imagecreatefromjpeg($imgPath);
    $color = imagecolorallocate($image, 234, 222, 222 );
   $fontSize = 25;
    $x = 30;
    $y = 15;
    imagestring($image, $fontSize, $x, $y, $string, $color);
     return imagejpeg($image);

In the code above, we created a captcha function. You will need a background.jpg image. Find a background.jpg on the internet like – a black background image and resize the image – Size 133X41 also rename and save it as background.jpg in the same path. 
As you can see the code line in the JS file – 
  $('#subloader').html('<img src="loader.gif" height="100">');
You will need a loader gif image. Find a loader gif from the internet and save it in the same folder path. 
The loader will display when the user will click on the send message button and remove when the message is sent or if something is wrong. 
You can execute the contac.php file but there is a file missing. 
Let’s design the contact form using the extra stylesheet. 


background-color: #f1f1f1;
    font-weight: 700;
    line-height: 1.5;
    color: #000;
    font-family: lora,serif;
  box-shadow: 0px -12px 24px rgb(47 65 129 / 10%);
   padding: 20px;
    border-radius: 20px;
    background-color: #fff;
    margin-top: 10px ;
    input, textarea, select {
    padding: 10px 20px;
    color: #1E266D;
    width: 100%;
    height: 50px;
    background: #F5FAFF !important;
    border: 1px solid #EEF1FF;
    border-radius: 5px;

Kindly set email credentials in the action PHP file. In this tutorial, we used the PHP mail() function to create a contact form but rather than the mail() function, we can use the PHPMailer library and HOST SMTP to send the email. Kindly execute the contact page on the live server (Hosting). The mail() function works on a live server. In this way, You can easily create a contact form using PHP and AJAX with captcha validation. 

Please Share

Recommended Posts:-