What are the best practices for handling form data in PHP, specifically when sending emails?
When handling form data in PHP, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. When sending emails, make sure to properly format the email content and headers to prevent email injection attacks. Use PHP's built-in functions like filter_var() for input validation and mail() function for sending emails securely.
<?php
// Sanitize and validate form data
$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 email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
exit;
}
// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$mailBody = "Name: $name\n";
$mailBody .= "Email: $email\n";
$mailBody .= "Message: $message";
mail($to, $subject, $mailBody, $headers);
echo "Email sent successfully";
?>
Keywords
Related Questions
- What are the limitations of using PHP for client-side interactions compared to JavaScript?
- How can the variable $showFormular be effectively utilized to control form display in PHP?
- What strategies can be used to maintain code organization and avoid complexity when working with PHP functions for user registration?