What are the best practices for handling form data in PHP to ensure proper formatting and display in emails?
When handling form data in PHP for email submissions, it is important to sanitize and validate the input to prevent any malicious code injection. Additionally, formatting the data properly before sending it in the email ensures that it displays correctly for the recipient. Using PHP functions like htmlspecialchars() to sanitize user input and nl2br() to convert new lines to HTML line breaks can help ensure proper formatting and display in emails.
// Sanitize form data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// Format data for email display
$message = nl2br($message);
// Send email
$to = "recipient@example.com";
$subject = "New Form Submission";
$body = "Name: $name <br>Email: $email <br>Message: $message";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: sender@example.com' . "\r\n";
mail($to, $subject, $body, $headers);
Keywords
Related Questions
- What are the implications of recompiling PHP with modified mail function for Windows servers?
- How can form data submitted using "submit" be directly transferred into an array in PHP?
- How does the nl2br function in PHP compare to using regular expressions for replacing \n with <br> in text manipulation tasks?