What are common pitfalls when using PHP for form handling and email generation?

Common pitfalls when using PHP for form handling and email generation include not properly sanitizing user input, not validating form data, and not handling errors effectively. To solve these issues, always sanitize user input to prevent SQL injection and cross-site scripting attacks, validate form data to ensure it meets the expected format, and handle errors gracefully to provide a better user experience.

// Sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Validate form data
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Handle invalid email address
}

// Handle errors effectively
if (mail('recipient@example.com', 'Subject', $message, 'From: ' . $email)) {
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email';
}