What are some best practices for beginners when working on a formmail project in PHP?
Issue: One common issue beginners face when working on a formmail project in PHP is not properly sanitizing user input before sending it via email. This can lead to security vulnerabilities such as injection attacks. To solve this issue, it is important to sanitize and validate user input before processing and sending it in the email. Code snippet:
// Sanitize and validate user input before sending it via email
$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 address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
exit;
}
// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
if (mail($to, $subject, $body)) {
echo "Email sent successfully";
} else {
echo "Error sending email";
}