php

Create Contact Form Using HTML and PHP

Contact form is a very essential part of any website. The visitors of the site need to communicate with the site owner for different purposes. By using the contact form, the visitors send messages to the administrator or site owner with the contact information. The administrator or site owner can respond to the visitors after reading and considering the importance of their message. You can create a contact form for any site in various ways. How you can create a simple contact form and responsive contact form by using HTML, CSS, Bootstrap, and PHP has been shown in this tutorial.

Simple Contact Form

The way of designing a simple contact form by using HTML, CSS, and PHP has been shown in this part of the tutorial.

HTML and CSS Code:

Create a PHP file named simple_contact_form.php with the following script to display the contact form by using HTML and CSS only. The PHP script will be added later to validate the form and display the submitted form data.

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Contact Form</title>
<link href="style.css" rel="stylesheet" />

<!--Add CSS code-->
<style>
/* Change the look of Labels */
label {
    display:block;
    margin-top:20px;
    letter-spacing:2px;
}

/* Center the form  */
form {
    margin:0 auto;
    width:450px;
}

/* textbox and textarea styles */
input, textarea {
    width:430px;
    height:25px;
    background: #E5FCDF;
    padding:10px;
    margin-top:3px;
    color: #4A2A2B;
    border-radius:7px;
    border:1px solid green;
}

/* height for textarea */
textarea {
    height:213px;

}

/* Border style on focus */
input:focus, textarea:focus {
    border:1px solid #97d6eb;
}

/* submit button styles */
#submit {
    width:130px;
    height:40px;
    margin-top:20px;
    margin-bottom:20px;
    cursor:pointer;
    color:#363E3F;
}

/* Change button looks on hover */
#submit:hover {
    opacity:0.5;
}
</style>

</head>

<body>

<div style="background-color:#F0F7F6; width:50%; margin:40px auto;" >
    <h2 align="center" style="  background: #DCF5FD; height:30px; color: #807A7A" >
    CONTACT FORM
    </h2>

        <form method="post" action="#">
       
            <label>Name</label>
            <input name="name" placeholder="Enter Your name" value="<?php echo $name ?>" />
            <div style="color:red"><?php echo $nameerr ?></div>
                   
            <label>Email</label>
            <input name="email" type="email" value="<?php echo $email ?>" placeholder="Enter your email" />
            <div style="color:red"><?php echo $emailerr ?></div>

            <label>Message</label>
            <textarea name="message" placeholder="Type Your message"><?php echo $message ?></textarea>
            <div style="color:red"><?php echo $messageerr ?></div>

            <input id="submit" name="submit" type="submit" value="Submit" />
        </form>
</div>
</body>
</html>

Now, run the simple_contact_form.php file from the server. The following output will appear after executing the script.

Read, Validate and Print the Form Data Using PHP

Now, add the following PHP script at the beginning of the simple_contact_form.php file to validate the form data, read form data, and print the data on the browser. When the user will click Submit button, then the form data will be checked for validation by using PHP script. If the submitted data will be validated, then the data will be printed in the browser.

PHP Code:

Add the following PHP code at the beginning of the simple_contact_form.php file.

<?php
    $name = "";
    $nameerr = "";

    $email = "";
    $emailerr = "";

    $message = "";
    $messageerr = "";

    $error = false;

    /* Check required fields */
    if(isset($_POST['submit']))
    {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];

        if($name == "")
        {
            $nameerr = "Field can't be empty.";
            $error = true;
        }
        else if(strlen($name) < 3)
        {
            $nameerr = "Name should be more than 2 characters.";
            $error = true;
        }
        else
        {
            $nameerr = "";
        }
   
        if($email == "")
        {
            $emailerr = "Field can't be empty.";
            $error = true;
        }
        else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
        {
            $emailerr = "Invalid email address.";
            $error = true;
        }
        else
        {
            $emailerr = "";
        }

        if($message == "")
        {
            $messageerr = "Field can't be empty.";
            $error = true;
        }
        else if(strlen($message) < 10)
        {
            $messageerr = "Message should be more than 9 characters.";
            $error = true;
        }
        else
        {
            $messageerr = "";
        }

        if($error == false)
        {
            $name = $name;
            $to = '[email protected]';
            $from = $email;
            $subject = 'Inquiry';
            $body = 'Hello,<br/><br/>'.$message.'<br/><br/>Thanks, <br/>'.$name;
   
            echo "To: ".$to."<br/>From: ".$from."<br/>Subject: ".$subject."<br/><hr><br/>".$body;  
        }
    }
    if(!isset($_POST['submit']) || $error == true)
    {

?>

Add the following PHP code at the end of the simple_contact_form.php file.

<?php
    }
?>

If the form is submitted by keeping all fields empty, then the following output will appear.

If the form is submitted by typing less than 9 characters in the message fields, then the following output will appear.

If the form is submitted with all valid data, then the following output will appear.

By using the above codes you can easily create a very simple contact form for your site. But this form is not a responsive contact form. The way of making this form responsive has been shown in the next part of this tutorial.

Responsive Contact Form

Most of the websites are designed with responsive features now. The way of converting the previously created simple contact form into a responsive contact form by using Bootstrap has been shown in this part of the tutorial.

HTML Code:

Create a PHP file named responsive_contact_form.php with the following script to display the responsive contact form by using HTML and Bootstrap. The PHP script will be added later to validate the form and display the submitted form data.

<html>
<head>
<title>Contact Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">

</head>
<body>
<!-- Wrapper container -->
<div class="container">
  <div class="row mb-3">
  <div class="mb-3 col-sm-8 offset-sm-2"><center><h3 class="mt-5">Contact Form<</h3></center></div>
  <!-- Bootstrap 5 form -->
  <form method="post" acrion="#" >

    <!-- Name input -->
    <div class="mb-3 col-sm-8 offset-sm-2">
      <label class="form-label" for="name">Name</label>
      <input class="form-control" name="name" placeholder="Enter Your name" value="<?php echo $name ?>" required />
      <div style="color:red"><?php echo $nameerr ?></div>    </div>

    <!-- Email address input -->
    <div class="mb-3 col-sm-8 offset-sm-2">
      <label class="form-label" for="emailAddress">Email Address</label>
      <input class="form-control" name="email" type="email" value="<?php echo $email ?>" placeholder="Enter your email" required />
      <div style="color:red"><?php echo $emailerr ?></div>
    </div>

    <!-- Message input -->
    <div class="mb-3 col-sm-8 offset-sm-2">
      <label class="form-label" for="message">Message</label>
      <textarea class="form-control" name="message" placeholder="Type Your message" required><?php echo $message ?></textarea>
      <div style="color:red"><?php echo $messageerr ?></div>
    </div>

    <!-- Form submit button -->
    <div class="d-grid col-sm-8 offset-sm-2">
      <button class="btn btn-primary btn-lg" name="submit" type="submit">Submit</button>
    </div>

  </form>

</div>
    </div>
</body>
</html>

If you enable the responsive feature of the browser, then the form will be looked like the following image.

PHP Code:

Now, add the previously shown PHP script in the responsive_contact_form.php file like the simple_contact_form.php file to check the validation is working or not.

If the form is submitted by typing less than 9 characters in the message fields, then the following output will appear.

If the form is submitted with all valid data, then the following output will appear.

Conclusion

Two ways of using the contact form by using PHP have been shown in this tutorial. If you want to send the data to the site owner or administrator, then you can use the PHP mail() function or any PHP library for sending an email with form data.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.