PHP Contact Form with Sending Email

In this tutorial, I have provided the standard script to create a simple PHP contact form. It is created with complete back-end validation and sending email feature. It is also very simple to integrate easily on the website. So, you should use it in your project.

The contact form is the most important part of websites. It can help the users to communicate with the Website owner. So, Users can send a mail to the website owner through it and get a quick response.

PHP Contact Form

 Create PHP Contact Form to Send Email with Validation

PHP Contact Form contains four input fields like Full Name, Email, Subject, Message. These fields will not accept invalid data. It has also a send Message button. This button will help to send your message request whenever you click on it after entering your contact message.

Features:

  • It is created with a professional UI.
  • It is developed with complete validations.
  • Visitors can quickly send emails without login into an email account.
  • Even It will save visitors contact information into the database
  • It is easy to integrate on the website.
  • It is absolutely free to use.

Read also –

jQuery Form Validation

Folder Structure –

Create a folder structure like the following view for the testing contact form. Otherwise, You can use the given script directly in your project.

myprojects/
    |__contact-form.php
    |__contact-script.php
    |

1. Create a MySQL Database and Table

You should create a MySQL database using the following Query.

$query = "CREATE DATABASE codingstatus";

Also, Create a contact Table in the MySQL database using the following query.

CREATE TABLE `contact` (
`id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
`full_name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`subject` varchar(255) DEFAULT NULL,
`message` varchar(255) DEFAULT NULL,
`created_at` timestamp(6) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

2. Connect Contact Form Script to MySQL Database

First, You have to connect the contact form script to MySQL Database by writing the following database connection query. Even you can replace connection details like hostname, username, password & table name with your connection details

<?php
$hostname     = "localhost"; // Enter Your Host Name
$username     = "root";      // Enter Your Table username
$password     = "";          // Enter Your Table Password
$databasename = "codingstatus"; // Enter Your database Name

$conn = new mysqli($hostname, $username, $password, $databasename);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}


?>

 

3. Create Contact Form Using HTML

Write the following code in contact-form.php

  • Include contact-script.php using include() method.
  • This contact form is created using bootstrap4. You should include the following its CDN.
  • Write the HTML code to create a contact form.
  • The name of every field should be the same as the column name of the MySQL table.
  • Some PHP script is written with this form. So, you should not worry, It will be explained in the next step.

File Name – contact-form.php

<?php
include('contact-script.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Contact Form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
  <!--bootstrap4 library linked-->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <!--custom style-->
 <style type="text/css">
     .contact-form{
      background: #f7f7f7;
      padding: 20px;
      border: 1px solid orange;
      margin: 50px 0px;
    }
    .err-msg{
      color:red;
    }
    .contact-form form{
      border: 1px solid #e8e8e8;
      padding: 10px;
      background: #f3f3f3;
    }
 </style>
</head>
<body>
<div class="container-fluid">
 <div class="row">
   <div class="col-sm-4">
   </div>
   <div class="col-sm-4">
    
    <!--====registration form====-->
    <div class="contact-form">
      <h4 class="text-center">PHP Contact Form</h4>
      <p class="text-success text-center"><?php echo $contact_us; ?></p>
      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
       
         <!--// Email//-->
        <div class="form-group">
            <label>Full Name:</label>
            <input type="text" class="form-control" placeholder="Enter Full Name" name="full_name" value="<?php echo $set_name;?>">
            <p class="err-msg">
            <?php if($nameErr!=1){ echo $nameErr; } ?>
            </p>
        </div>
        <!--// Email//-->
        <div class="form-group">
            <label>Email:</label>
            <input type="text" class="form-control" placeholder="Enter email" name="email" value="<?php echo $set_email;?>">
            <p class="err-msg">
            <?php if($emailErr!=1){ echo $emailErr; } ?>
            </p>
        </div>
        
        <!--//Password//-->
        <div class="form-group">
            <label>Subject:</label>
            <input type="text" class="form-control"  placeholder="Enter Subject" name="subject" value="<?php echo $set_subject;?>">
            <p class="err-msg">
            <?php if($subjectErr!=1){ echo $subjectErr; } ?>
            </p>
        </div>
        <div class="form-group">
          <label>Message</label>
          <textarea class="form-control" name="msg" placeholder="Enter Message">
            <?php echo $set_msg;?>
          </textarea>
           <p class="err-msg">
            <?php if($msgErr!=1){ echo $msgErr; } ?>
            </p>
        </div>
        <input type="submit" class="btn btn-danger" value="Send Message" name="contact">
      </form>
    </div>
   </div>
   <div class="col-sm-4">
   </div>
 </div>
  
</div>

</body>
</html>

 

4. Create Contact Form Script Using PHP

To create a PHP Contact Form Script, You should know the following points for a better understanding of its concept.

  • First, Include the MySQL database connection file using require_once('database.php')
  • Assign $conn variable to a new variable $db
  • Validate the user Input after submitting the contact form
  • If all the input fields are validated successfully, call the following two custom functions.
    • send_mail() – This function will send a contact mail to the website owner. If the message will be sent successfully. you will get a success message.
    • store_message() –  This function will store contact input data in the MySQL database.

File Name – contact-script

<?php
require_once('database.php');
$db= $conn;
$contact_us=$nameErr=$emailErr=$subjectErr=$msgErr='';
// set empty input value into the contact field
$set_name=$set_email=$set_subject=$set_msg='';


extract($_POST);
if(isset($contact))
{
   
   //regular expression
   $validName="/^[a-zA-Z ]*$/"; // full Name
   $validEmail="/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/"; // Email
   
 
 //Full Name Validation
if(empty($full_name)){
  $nameErr="Full Name is Required"; 
}
else if (!preg_match($validName,$full_name)) {
  $nameErr="Only Characters and white spaces are allowed";
}
else{
  $nameErr=true;
}
//Email Address Validation
if(empty($email)){
  $emailErr="Email is Required"; 
}
else if (!preg_match($validEmail,$email)) {
  $emailErr="Invalid Email Address";
}
else{
  $emailErr=true;
}

//Subject Name Validation
if(empty($subject)){
  $subjectErr="Subject is Required"; 
}else{
  $subjectErr=true;
}
    
//message Validation
if(empty($msg)){
  $msgErr="Message is Required"; 
}else{
  $msgErr=true;
}



// check all fields are valid or not
if( $nameErr==1 && $emailErr==1 && $subjectErr==1 && $msgErr==1)
{
 
   //legal input values
   $fullName=  legal_input($full_name);
   $emailAddress=  legal_input($email);
   $subject=  legal_input($contact);
   $message=  legal_input($msg);
   
   // call fucntion to store contact message
   store_message($fullName,$emailAddress,$subject,$message)
   // function whic is contained sending mail script
   $contact_us=send_mail($fullName,$emailAddress,$subject,$message);
}
else{
    // set user input value into the contact field

  $set_name    = $full_name;
  $set_email   = $email;
  $set_subject = $subject;
  $set_msg     = $msg;
}
}
// convert illegal input value to ligal value formate
function legal_input($value) {
  $value = trim($value);
  $value = stripslashes($value);
  $value = htmlspecialchars($value);
  return $value;
}
// function to send mail to the website owner
function send_mail($fullName,$emailAddress,$subject,$message){
   
  
            $to = 'codingstatus@gmail.com'; // Enter Website Owner Email
            $subject = 'Contact Message was sent by'.$fullName;
            $message = '<h2>Contact Message Details</h2>
                      <h3>Full Name</h3>
                      <p>'.$fullName.'</p>
                      <h3>Email Address</h3>
                      <p>'.$emailAddress.'</p>
                      <h3>Subject</h3>
                      <p>'.$subject.'</p>
                      <h3>Message</h3>
                      <p>'.$message.'</p>';
            
            // Set content-type header for sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= 'From: '.$emailAddress.'('.$fullName.')'. "\r\n";
            
            // Send email
            if(mail($to,$subject,$message,$headers)){
                 return 'Your Message was sent Successfully';
               
            }else{
                return 'Message is unable to send, please try again.';
                
            }
}


// function to insert user data into database table
function store_message($fullName,$emailAddress,$subject,$message){

   global $db;
   $sql="INSERT INTO contact (full_name,email,subject,message) VALUES(?,?,?,?)";
   $query=$db->prepare($sql);
   $query->bind_param('ssss',$fullName,$email,$subject, $message);
   $exec= $query->execute();
    if($exec==true)
    {
     return "You are registered successfully";
    }
    else
    {
      return "Error: " . $sql . "<br>" .$db->error;
    }
}

?>

 

Summary –

I hope that the above script is useful to you. Now you can easily create the Contact form using PHP for your project. If you have any doubts or questions related to this tutorial, you can ask me through the below comment box. I will reply as soon as possible.

Thanks For giving time on this tutorial…