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 advantages of using an HTML parser over regex for extracting data from HTML content in PHP?
- What considerations should be taken into account when designing a system to display user-generated content on a social network platform in a way that optimizes performance and user experience?
- What are some potential pitfalls of using sprintf in PHP for formatting data, and how can developers troubleshoot and resolve these issues effectively?