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.


  • 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.


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` (
`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,


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

$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

<!DOCTYPE html>
<html lang="en">
  <title>PHP Contact Form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!--bootstrap4 library linked-->
  <link rel="stylesheet" href="">
  <script src=""></script>
  <script src=""></script>
  <script src=""></script>
  <!--custom style-->
 <style type="text/css">
      background: #f7f7f7;
      padding: 20px;
      border: 1px solid orange;
      margin: 50px 0px;
    .contact-form form{
      border: 1px solid #e8e8e8;
      padding: 10px;
      background: #f3f3f3;
<div class="container-fluid">
 <div class="row">
   <div class="col-sm-4">
   <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; } ?>
        <!--// Email//-->
        <div class="form-group">
            <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; } ?>
        <div class="form-group">
            <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; } ?>
        <div class="form-group">
          <textarea class="form-control" name="msg" placeholder="Enter Message">
            <?php echo $set_msg;?>
           <p class="err-msg">
            <?php if($msgErr!=1){ echo $msgErr; } ?>
        <input type="submit" class="btn btn-danger" value="Send Message" name="contact">
   <div class="col-sm-4">



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

$db= $conn;
// set empty input value into the contact field

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

//Subject Name Validation
  $subjectErr="Subject is Required"; 
//message Validation
  $msgErr="Message is Required"; 

// 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
   // function whic is contained sending mail script
    // 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 = ''; // Enter Website Owner Email
            $subject = 'Contact Message was sent by'.$fullName;
            $message = '<h2>Contact Message Details</h2>
                      <h3>Full Name</h3>
                      <h3>Email Address</h3>
            // 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
                 return 'Your Message was sent Successfully';
                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->bind_param('ssss',$fullName,$email,$subject, $message);
   $exec= $query->execute();
     return "You are registered successfully";
      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…