How can PHP beginners avoid common pitfalls when sending emails from a form?
One common pitfall when sending emails from a form in PHP is not properly sanitizing user input, which can lead to security vulnerabilities such as injection attacks. To avoid this, always validate and sanitize user input before using it in the email headers or body. Additionally, make sure to handle errors gracefully and provide informative feedback to users if the email fails to send.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$headers = "From: $name <$email>";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully";
} else {
echo "Failed to send email";
}
}
?>
Keywords
Related Questions
- What are the potential pitfalls of using the jpg2pixmap function in the PHP code?
- What role does the encoding declaration (e.g., UTF-8 without BOM) play in resolving Umlaut encoding issues in PHP scripts when interacting with external APIs or websites?
- What are some recommended PHP books for beginners looking to learn PHP5 and database connectivity?