How can PHP be utilized to send form data via email and ensure proper formatting?
To send form data via email using PHP and ensure proper formatting, you can use the PHP `mail()` function to send the email with the form data as the message content. You can also use headers to set the email format as HTML to ensure proper formatting. Additionally, you can sanitize and validate the form data before sending it to prevent any malicious content or errors in the email.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$to = "recipient@example.com";
$subject = "Form Submission";
// Sanitize and validate form data
$name = htmlspecialchars($_POST["name"]);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars($_POST["message"]);
// Set email headers for proper formatting
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: " . $email . "\r\n";
// Compose the email message with form data
$email_message = "<html><body>";
$email_message .= "<h1>New Form Submission</h1>";
$email_message .= "<p>Name: " . $name . "</p>";
$email_message .= "<p>Email: " . $email . "</p>";
$email_message .= "<p>Message: " . $message . "</p>";
$email_message .= "</body></html>";
// Send the email
mail($to, $subject, $email_message, $headers);
echo "Email sent successfully!";
}
?>
Keywords
Related Questions
- What potential pitfalls should be considered when parsing and extracting data from a text file using PHP?
- What considerations should be taken into account when deciding whether to concatenate email addresses into a single string or keep them as an array within a PHP class method?
- What are the best practices for handling data retrieval and manipulation in PHP scripts?