How can PHP beginners ensure that all form fields are correctly captured and sent via email in a PHP script?

To ensure that all form fields are correctly captured and sent via email in a PHP script, beginners should validate and sanitize the input data before sending it. This helps prevent any errors or malicious code from being executed. Additionally, make sure to include all form fields in the email body or attachment when sending the email.

// Validate and sanitize form input
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) : '';
$message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '';

// Create email message
$to = 'recipient@example.com';
$subject = 'Contact Form Submission';
$body = "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Message: $message\n";

// Send email
if(mail($to, $subject, $body)){
    echo 'Email sent successfully';
} else {
    echo 'Error sending email';
}