What best practices should be followed when setting up a simple form for email submission using PHP?
When setting up a simple form for email submission using PHP, it is important to validate user input to prevent malicious code injection and ensure the data submitted is in the correct format. Additionally, it is crucial to sanitize the input to remove any unwanted characters or tags. Lastly, always use a secure method to send the email, such as PHP's built-in mail function or a third-party library like PHPMailer.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$to = "recipient@example.com";
$subject = "New email submission";
$message = "Email: " . $email;
if(mail($to, $subject, $message)){
echo "Email sent successfully!";
} else {
echo "Failed to send email. Please try again.";
}
} else {
echo "Invalid email address. Please enter a valid email.";
}
}
?>