What are the best practices for handling form submissions and sending emails in PHP?
When handling form submissions and sending emails in PHP, it is important to validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting. Additionally, always sanitize and escape user input before using it in database queries or email content to prevent malicious code execution. Finally, use a reliable email library or service to send emails securely and efficiently.
// Example of handling form submission and sending email in PHP
// Validate and sanitize form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Send email using PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress($email, $name);
$mail->isHTML(true);
$mail->Subject = 'Thank you for your message';
$mail->Body = 'Your message: ' . $message;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
Keywords
Related Questions
- In PHP, what are the advantages of using fetchAll(PDO::FETCH_COLUMN) with PDO for fetching data from a database query?
- What potential pitfalls should be considered when implementing a preview functionality for user input in PHP?
- What are the potential pitfalls of using utf8_encode and utf8_decode in data processing?