Create a simple but secure Contact Form with PHP and Javascript

In this post, we will create a simple yet secure contact form using PHP for server-side processing and JavaScript for client-side validation. The form will include fields for the user’s name, email, subject, and message. We will implement error handling and exception handling to ensure robustness and security.

HTML Form

First, we will create the HTML structure for the contact form. This form will include basic validation using JavaScript.

<!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>
    <script>
        function validateForm() {
            const name = document.forms["contactForm"]["name"].value;
            const email = document.forms["contactForm"]["email"].value;
            const subject = document.forms["contactForm"]["subject"].value;
            const message = document.forms["contactForm"]["message"].value;

            if (name === "" || email === "" || subject === "" || message === "") {
                alert("All fields must be filled out.");
                return false;
            }

            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailPattern.test(email)) {
                alert("Please enter a valid email address.");
                return false;
            }

            return true;
        }
    </script>
</head>
<body>
    <h2>Contact Us</h2>
    <form name="contactForm" action="process_form.php" method="post" onsubmit="return validateForm()">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name"><br>
        <label for="email">Email:</label><br>
        <input type="text" id="email" name="email"><br>
        <label for="subject">Subject:</label><br>
        <input type="text" id="subject" name="subject"><br>
        <label for="message">Message:</label><br>
        <textarea id="message" name="message"></textarea><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

PHP Processing Script

Next, we will create the process_form.php file to handle the form submission. This script will include error handling and exception handling to manage any issues that may arise during processing.

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

    // Validate input
    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        die("Error: All fields are required.");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die("Error: Invalid email format.");
    }

    // Prepare email
    $to = "your-email@example.com"; // Replace with your email
    $headers = "From: $name <$email>\r\n";
    $headers .= "Reply-To: $email\r\n";

    // Send email
    try {
        if (!mail($to, $subject, $message, $headers)) {
            throw new Exception("Error: Email could not be sent.");
        }
        echo "Success: Your message has been sent.";
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo "Error: Invalid request method.";
}
?>
  1. HTML Form: The form collects user input and uses JavaScript for basic validation before submission.
  2. PHP Script: The script processes the form data, validates it, and sends an email. It includes error handling to manage empty fields and invalid email formats, as well as exception handling for email sending failures.

By following this structure, you can create a secure contact form that effectively handles user input and potential errors.

Happy coding… 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *