What are some best practices for handling email functionality in PHP scripts to avoid errors like the one mentioned in the forum thread?
Issue: The error mentioned in the forum thread could be due to improper handling of email functionality in PHP scripts, such as not setting headers correctly or not validating user inputs before sending emails. To avoid such errors, it is crucial to follow best practices like sanitizing user inputs, setting proper headers, and using a reliable email library. Code snippet:
// Sanitize user inputs
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Set proper headers
$headers = "From: $name <$email>" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\r\n";
// Send email using a reliable library like PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->setFrom($email, $name);
$mail->addAddress('recipient@example.com');
$mail->Subject = 'New message from website';
$mail->Body = $message;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
Related questions
-
Variable definitions inclusion of external files dynamic content generation
-
file paths directory paths errors
-
SQL functions date_format date manipulation