What are the best practices for handling form submission in PHP to ensure all data is properly processed and sent via email?
When handling form submissions in PHP, it is important to properly sanitize and validate the data to prevent security vulnerabilities and ensure accurate processing. One way to achieve this is by using PHP's filter_input function to sanitize input data and validate it before sending it via email. Additionally, it is recommended to use PHP's built-in mail function to send the form data securely.
<?php
// Sanitize and validate form data
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
// Check if all required fields are filled
if ($name && $email && $message) {
// Compose email message
$to = "recipient@example.com";
$subject = "New 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 "Failed to send email";
}
} else {
echo "All fields are required";
}
?>