What are best practices for formatting and sending form data via email in PHP?
When sending form data via email in PHP, it is important to properly format the email content to ensure readability and organization. One common practice is to use HTML formatting to structure the email with headers, paragraphs, and lists. Additionally, it is recommended to sanitize and validate the form data before including it in the email to prevent any security vulnerabilities.
<?php
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Compose email content with HTML formatting
$to = 'recipient@example.com';
$subject = 'New Form Submission';
$headers = 'From: ' . $email . "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'Content-Type: text/html; charset=UTF-8\r\n';
$body = '<html><body>';
$body .= '<h2>New Form Submission</h2>';
$body .= '<p><strong>Name:</strong> ' . $name . '</p>';
$body .= '<p><strong>Email:</strong> ' . $email . '</p>';
$body .= '<p><strong>Message:</strong> ' . $message . '</p>';
$body .= '</body></html>';
// Send email
mail($to, $subject, $body, $headers);
?>