Php mail contact form

Here is an example of a simple PHP contact form that sends an email:

index.php

<?php
// Configuration
$to_email = '[email protected]'; // Replace with your email address
$subject = 'Contact Form Submission';

// Form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Validate form data
if (empty($name) || empty($email) || empty($message)) {
    echo 'Please fill out all fields!';
    exit;
}

// Send email
$headers = 'From: '. $email. "\r\n";
$headers.= 'Reply-To: '. $email. "\r\n";
$headers.= 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";

$message_text = "Name: $name\nEmail: $email\nMessage: $message";
mail($to_email, $subject, $message_text, $headers);

// Display success message
echo 'Thank you for contacting us!';
?>

contact_form.html

<form action="index.php" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <label for="message">Message:</label>
    <textarea id="message" name="message"></textarea><br><br>
    <input type="submit" value="Send">
</form>

How it works:

  1. The form is submitted to the index.php file using the POST method.
  2. The index.php file checks if all form fields are filled out. If not, it displays an error message and exits.
  3. The form data is validated and sanitized.
  4. The email is sent using the mail() function, with the form data as the message body and the recipient's email address as the To field.
  5. The email is sent with a From field set to the user's email address, and a Reply-To field set to the same email address.
  6. The email is sent with a MIME-Version and Content-Type header set to text/plain, indicating that the message body is plain text.
  7. The index.php file displays a success message after the email is sent.

Security notes: