How can error handling be improved in the PHP code snippet provided for sending form emails?
The issue with the provided PHP code snippet for sending form emails is that it lacks proper error handling. To improve error handling, we can implement try-catch blocks to catch any exceptions that may occur during the email sending process. This will help in identifying and handling errors more effectively.
<?php
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Email variables
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$message = $_POST['message'];
$headers = "From: " . $_POST['email'];
try {
// Attempt to send email
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
throw new Exception("Failed to send email.");
}
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
}
?>