How To Create an Easy PHP Contact Form
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
Creating a contact form is a fundamental task for any website. It allows visitors to get in touch with the site owner easily. In this guide, we will walk you through creating a simple and effective PHP contact form, ensuring that it’s secure and easy to implement. By the end of this post, you’ll have a fully functional contact form script that you can integrate into your website.
Step 1: Set Up Your Project
Before we dive into the code, ensure you have a PHP environment set up on your server or local machine. You’ll need:
- A web server (like Apache or Nginx)
- PHP installed
- A text editor or IDE
Step 2: Create the HTML Form
First, let’s create the HTML form. Create a file named contact.html and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Us</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 50px; }
        form { max-width: 600px; margin: auto; }
        label { display: block; margin-top: 10px; }
        input, textarea { width: 100%; padding: 10px; margin-top: 5px; }
        button { padding: 10px 15px; margin-top: 10px; background-color: #28a745; color: #fff; border: none; cursor: pointer; }
        button:hover { background-color: #218838; }
    </style>
</head>
<body>
    <h1>Contact Us</h1>
    <form action="contact.php" method="post">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" required>
        
        <label for="email">Email</label>
        <input type="email" id="email" name="email" required>
        
        <label for="message">Message</label>
        <textarea id="message" name="message" rows="5" required></textarea>
        
        <button type="submit">Send Message</button>
    </form>
</body>
</html>
Step 3: Create the PHP Script
Now, let’s create the PHP script that will handle the form submission. Create a file named contact.php and add the following code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form inputs
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));
    $message = htmlspecialchars(trim($_POST['message']));
    // Validate inputs
    if (empty($name) || empty($email) || empty($message)) {
        echo "All fields are required.";
        exit;
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
        exit;
    }
    // Prepare the email
    $to = "[email protected]"; // Replace with your email
    $subject = "Contact Form Submission from $name";
    $body = "Name: $name\nEmail: $email\n\nMessage:\n$message";
    $headers = "From: $email";
    // Send the email
    if (mail($to, $subject, $body, $headers)) {
        echo "Thank you for your message. We will get back to you soon.";
    } else {
        echo "Sorry, there was an error sending your message. Please try again later.";
    }
} else {
    echo "Invalid request method.";
}
?>
Explanation of the PHP Script
- Form Submission Check: The script checks if the request method is POST, ensuring that the form was submitted correctly.
- Input Sanitization and Validation: The htmlspecialcharsfunction is used to sanitize inputs, andtrimremoves any extra spaces. The script then checks if any field is empty and if the email format is valid.
- Email Preparation: The script sets up the email parameters, including the recipient’s email, subject, body, and headers.
- Email Sending: The mailfunction is used to send the email. A success or error message is displayed based on the result.
Step 4: Enhancing Security
While the above script covers basic functionality, consider these additional security measures:
- CAPTCHA: Implement a CAPTCHA to prevent spam submissions.
- CSRF Protection: Use tokens to protect against Cross-Site Request Forgery.
- Rate Limiting: Limit the number of submissions per IP address to prevent abuse.
Conclusion
Creating a simple PHP contact form is straightforward and involves just a few steps: setting up the HTML form, handling form submission with PHP, and sending the email. By following this guide, you can quickly implement a contact form on your website, making it easier for visitors to get in touch with you. Always remember to enhance your form’s security to protect against spam and abuse.