What are the best practices for handling form data in PHP to ensure all submitted information is correctly processed and included in the email?
When handling form data in PHP, it is important to properly sanitize and validate the input to prevent any security vulnerabilities or errors in processing the data. One way to ensure all submitted information is correctly processed and included in the email is to use PHP's filter_input function to retrieve and sanitize the form data before sending it in an email.
// Retrieve form data and sanitize
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
exit;
}
// Construct email message
$to = "recipient@example.com";
$subject = "New form submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
// Send email
mail($to, $subject, $body);
echo "Email sent successfully";
Keywords
Related Questions
- What are the important settings that beginners should configure when starting with PHP development?
- Are there any best practices to follow when integrating JavaScript with PHP for user interactions?
- Are there any best practices for handling form validation in PHP to avoid complex if-else conditions?