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);
Related Questions
- How can one ensure that all fields from a database are correctly transferred to a form in PHP?
- When seeking help in PHP forums for debugging issues, what information and details should be provided to effectively communicate the problem to others?
- What is the best practice for generating links with dynamic IDs in PHP?