Friday, September 20, 2024

Building a Simple PHP Contact Form with Email Functionality

In this tutorial, we will walk through the process of creating a basic contact form using PHP. We will cover the HTML structure, form validation, and the PHP code required to send an email with the form data. By the end of this tutorial, you will have a fully functional contact form that can be integrated into your website.

Prerequisites: Before you begin, make sure you have a basic understanding of HTML and PHP. Ensure that you have a local development environment set up with PHP installed.

Simple PHP Contact Form

First, let’s create the HTML structure for our contact form. Open a new file and paste the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
</head>
<body>
    <h2>Contact Us</h2>
    <form method="POST" action="process_form.php">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required>

        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required>

        <label for="message">Message:</label>
        <textarea name="message" id="message" required></textarea>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

Form Validation and Email Handling in PHP

Next, let’s create a new file called process_form.php. This file will handle the form submission and email functionality. Open the file and add the following code:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    // Validate form inputs (e.g., check if email is valid, required fields are not empty)

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Send email
        $to = "your-email@example.com";
        $subject = "New Contact Form Submission";
        $body = "Name: " . $name . "\n\nEmail: " . $email . "\n\nMessage: " . $message;

        if (mail($to, $subject, $body)) {
            echo "Thank you for your message! We will get back to you soon.";
        } else {
            echo "Oops! Something went wrong. Please try again later.";
        }
    } else {
        echo "Please enter a valid email address.";
    }
}
?>

Customize Email Settings

In the PHP code above, you need to replace "your-email@example.com" with your own email address. This is where the contact form submissions will be sent.

Conclusion

Congratulations! You have successfully built a simple contact form using PHP. We covered the HTML structure, form validation, and the PHP code required to handle form submissions and send emails. You can now integrate this contact form into your website to enable users to reach out to you. Feel free to enhance the form’s design and add additional validation as per your requirements. Happy coding!

Related Articles

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles