What are the best practices for handling line breaks and special characters in form data before sending emails in PHP?
When handling form data before sending emails in PHP, it is important to properly handle line breaks and special characters to ensure the email content is displayed correctly. To do this, you can use the PHP function `nl2br()` to convert line breaks to HTML `<br>` tags and `htmlspecialchars()` to encode special characters.
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Sanitize and format data
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$message = nl2br(htmlspecialchars($message));
// Send email
$to = 'recipient@example.com';
$subject = 'Message from ' . $name;
$body = "Name: $name <br>Email: $email <br>Message: $message";
$headers = 'Content-type: text/html';
mail($to, $subject, $body, $headers);