What are the best practices for creating a PHP script to handle form submissions and send emails with user input data?
When creating a PHP script to handle form submissions and send emails with user input data, it is important to sanitize and validate the user input to prevent security vulnerabilities. Additionally, use PHP's built-in mail function to send emails with the user input data. Finally, consider implementing error handling to provide feedback to the user in case of any issues.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars($_POST["message"]);
$to = "recipient@example.com";
$subject = "New Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
if (mail($to, $subject, $body)) {
echo "Email sent successfully.";
} else {
echo "Failed to send email.";
}
}
?>