What are common best practices for implementing an email form in PHP?
When implementing an email form in PHP, it is important to validate user input to prevent malicious code injection and ensure data integrity. Use PHP's built-in functions like filter_var() to validate email addresses and htmlspecialchars() to sanitize user input before sending the email. Additionally, always use a secure method like PHPMailer to send emails to prevent spam and ensure proper delivery.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
$message = htmlspecialchars($_POST["message"]);
if ($email && $message) {
require 'PHPMailer/PHPMailer.php';
$mail = new PHPMailer();
$mail->addAddress('recipient@example.com');
$mail->setFrom($email);
$mail->Subject = 'New message from contact form';
$mail->Body = $message;
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error sending email';
}
} else {
echo 'Invalid email or message';
}
}
?>
Keywords
Related Questions
- How can one optimize the architecture of a PHP project to load the page with a table first and then load data from a database into the table?
- How can the issue of additional 0-byte files being created alongside uploaded files be prevented in PHP?
- How can PHP be used to automatically call a function every 30 seconds without using sleep()?