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.
contact.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact Us </title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<link href="style.css" rel="stylesheet">
<script src="contact_scripts.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-2">
</div>
<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>
<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>
<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>
<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>
</select>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="label">Message </label>
<textarea name="msg" id="msg" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-2">
</div>
<div class="col-sm-4">
<label class="label"></label>
<br>
<span style="float: right;">
<img src="captchaimg.php" id="captcha"> <i class="fa fa-sync" aria-hidden="true" class=".refv" onClick="refreshCaptcha();"></i>
</span>
</div>
<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>
<div class="col-sm-2">
</div>
<div class="col-sm-12">
<div class="form-group text-center">
<br>
<button class="btn btn-primary" id="sendnow">Send Message </button>
<div id="subloader"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-2">
</div>
</div>
</div>
</body>
</html>
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 –
contact_scripts.js
$(document).ready(function(){
$("#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();
$.ajax({
method:"POST",
url: "contact_action.php",
data:{fname: fname, category: category, mobile: mobile, msg: msg, email: email, captcha_val: captcha_val },
beforeSend: function() {
$('#sendnow').hide();
$('#subloader').show();
$('#subloader').html('<img src="loader.gif" height="100">');
},
success: function(data){
//$('#msg').html(data);
var obj = JSON.parse(data);
$('#msg').html(obj.errors);
var status=obj.status ;
$('#subloader').hide();
$('#subloader').html("");
$('#sendnow').show();
if(status=='success')
{
$('#hide_form').hide();
$('#success').html('Thank you ' + fname + ' ! Your message has been sent . We will contcat you soon as possible.. ');
}
$("#captcha").attr('src','captchaimg.php');
}
});
});
});
function refreshCaptcha() {
$("#captcha").attr('src','captchaimg.php');
}
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.
contact_action.php
<?php session_start();
$fname=$_POST['fname'];
$category=$_POST['category'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];
$msg=$_POST['msg'];
$captcha_val=$_POST['captcha_val'];
$error= array();
if(strlen($fname)<2){
$error[] = 'Please enter Full Name using 3 charaters atleast.';
}
if(strlen($fname)>2){
if(!preg_match("/^[a-zA-Z\s]+$/", $fname)){
$error[] = 'Full Name:Characters Only (No digits or special charaters) ';
}
}
if(strlen($fname)>20){
$error[] = 'Full Name: Max length 20 Characters Not allowed';
}
if($email ==''){
$error[] = 'Please enter email';
}
if(strlen($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';
}
}
if(strlen($mobile)!=10){
$error[] = 'Mobile: Please enter 10 digits mobile number without country code';
}
if(strlen($category)==''){
$error[] = 'Please select service category';
}
if(strlen($msg)==''){
$error[] = 'Please enter your message';
}
if($captcha_val ==''){
$error[] = 'Please enter captcha';
}
if($captcha_val!='')
{
if ($_SESSION['captcha'] != $captcha_val)
{
$error[]='Invalid captcha';
}
}
$erro=array();
$i='<i class="fa fa-warning"></i>';
foreach($error as $err)
{
$erro[]=$i.' '.$err;
}
$error_str=implode('<br>', $erro);
if($error!=NULL)
{
$last_status='failed';
}
if($error==NULL){
$FromName='Techno Smarter';
$FromEmail='noreply@technosmarter.com';
$to_email='technosmarterinfo@gmail.com';
$ReplyTo=$email;
$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) ){
$last_status='success';
}
else {
$last_status="failed";
$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='noreply@technosmarter.com'; // your website official email like – noreply@domain.com
$to_email='technosmarterinfo@gmail.com'; // 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.
captchaimg.php
<?php session_start();
require("captcha.php");
$str=rand(100000,999999);
$_SESSION['captcha'] = $str;
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.
captcha.php
<?php
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.
style.css
body{
background-color: #f1f1f1;
}
h2{
font-weight: 700;
line-height: 1.5;
color: #000;
font-family: lora,serif;
}
.form-container
{
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;
}
textarea{
height:150px;
}
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.
Recommended Posts:-