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:
- The form is submitted to the
index.php
file using thePOST
method. - The
index.php
file checks if all form fields are filled out. If not, it displays an error message and exits. - The form data is validated and sanitized.
- The email is sent using the
mail()
function, with the form data as the message body and the recipient's email address as theTo
field. - The email is sent with a
From
field set to the user's email address, and aReply-To
field set to the same email address. - The email is sent with a
MIME-Version
andContent-Type
header set totext/plain
, indicating that the message body is plain text. - The
index.php
file displays a success message after the email is sent.
Security notes:
- This is a very basic example and should not be used in production without proper security measures.
- You should validate and sanitize all form data to prevent SQL injection and cross-site scripting (XSS) attacks.
- You should also consider using a more secure method of sending email, such as using a library like PHPMailer.
- You should also consider using a CAPTCHA to prevent spam submissions.