EN ES
Home > Web development > HTML Tutorials > How to Create a Contact Form in HTML

How to Create a Contact Form in HTML

Diego Cortés
Diego Cortés
July 30, 2024
How to Create a Contact Form in HTML

Introduction

In web development, contact forms are essential for allowing users to communicate with website owners. A well-designed contact form facilitates interaction and the collection of valuable information. In this guide, we'll show you how to create a contact form in HTML from scratch, covering both the basics and best practices to ensure it works correctly and is user-friendly.

What is a Contact Form in HTML?

An HTML contact form is a section on a website where users can send messages or requests to the website owner. Typically, it includes fields for the user to enter their name, email address, subject, and message. Contact forms can also include additional fields, such as phone numbers or checkboxes for preferences.

Basic Structure of a Contact Form

Here’s the basic structure of a simple contact form in HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 50%;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-group button {
            background-color: #5da269;
            color: #fff;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        .form-group button:hover {
            background-color: #4a8c5d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Contact Us</h1>
        <form action="process-form.php" method="post">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="email" id="email" name="email" required>
            </div>
            <div class="form-group">
                <label for="subject">Subject:</label>
                <input type="text" id="subject" name="subject" required>
            </div>
            <div class="form-group">
                <label for="message">Message:</label>
                <textarea id="message" name="message" rows="5" required></textarea>
            </div>
            <div class="form-group">
                <button type="submit">Send</button>
            </div>
        </form>
    </div>
</body>
</html>

PHP Code to Process the Form

Next, we need to add PHP code to handle the data submitted by the form. Create a file named process-form.php in the same directory as your HTML file and add the following code:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Receive form data
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    $subject = htmlspecialchars($_POST['subject']);
    $message = htmlspecialchars($_POST['message']);

    // Set the destination email address
    $recipient = "[email protected]"; // Change this to your email address

    // Set the email subject
    $emailSubject = "New contact message: $subject";

    // Build the message body
    $body = "Name: $name\n";
    $body .= "Email: $email\n";
    $body .= "Subject: $subject\n";
    $body .= "Message:\n$message\n";

    // Set the email headers
    $headers = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    // Send the email
    if (mail($recipient, $emailSubject, $body, $headers)) {
        echo "<p>Your message has been sent successfully. Thank you for contacting us.</p>";
    } else {
        echo "<p>There was a problem sending your message. Please try again later.</p>";
    }
} else {
    echo "<p>Unauthorized access.</p>";
}
?>

Explanation of the PHP Code

1. Validate Request Method

The PHP code begins by checking that the request is a POST. This ensures that the form processing only occurs when the form is submitted.

2. Receive and Sanitize Data

We use htmlspecialchars to prevent code injection and sanitize the data received from the form. This helps protect your website from scripting attacks (XSS).

3. Configure Email Settings

Define the destination email address and the email subject. Adjust $recipient with your email address to receive the messages.

4. Build and Send the Email

The message body is constructed with the form data. Email headers are set up for the email to be sent correctly. The mail() function is used to send the email.

5. Confirmation Message

A success message is displayed if the email is sent successfully, or an error message if there are issues.

Best Practices for Contact Forms

  1. Client-Side Validation: Use HTML5 attributes like required and type to validate data before it is sent to the server. This enhances user experience by providing immediate feedback.
  2. Security: Implement security measures like CSRF (Cross-Site Request Forgery) tokens to protect your form from malicious attacks.
  3. Accessibility: Ensure your form is accessible to all users, including those using assistive technologies. Use appropriate <label> tags and ensure all fields are keyboard accessible.
  4. Feedback: Provide clear and useful messages after the form is submitted, either to confirm that the message was sent or to inform the user about errors.
  5. Mobile Optimization: Ensure your form is fully functional on mobile devices by using responsive design techniques and adjusting the size of fields and buttons for smaller screens.

Conclusion

Creating a contact form in HTML is a fundamental task in web development. By following the steps outlined in this guide and adding the appropriate PHP processing, you can build a functional and attractive form that enhances communication with your users. Remember to apply best practices to ensure an optimal user experience and protect your website from potential threats. You are now ready to integrate effective contact forms into your web projects!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 22.98 ms