What are the potential issues with using the mail() function in PHP to send form data as text in an email?
One potential issue with using the mail() function in PHP to send form data as text in an email is that it may not properly handle special characters or HTML content, leading to formatting issues or potential security vulnerabilities. To solve this, you can use the PHP function htmlspecialchars() to encode special characters and prevent any HTML or script injections.
<?php
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Encode special characters in the message
$message = htmlspecialchars($message);
// Set up email headers
$to = 'recipient@example.com';
$subject = 'Form Submission';
$headers = 'From: ' . $email . "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Send the email
mail($to, $subject, $message, $headers);
?>