What best practices should be followed when writing PHP code for form processing and email sending?
When writing PHP code for form processing and email sending, it is important to sanitize user input to prevent SQL injection and cross-site scripting attacks. Additionally, always validate form data to ensure that it meets the required format before processing it. Finally, use PHP's built-in mail function or a trusted email library to securely send emails.
// Sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Validate form data
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Handle invalid email address
}
// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
if (mail($to, $subject, $body)) {
echo "Email sent successfully";
} else {
echo "Email sending failed";
}
Related Questions
- How can the "Cannot modify header information" warning be resolved in PHP?
- What are the common pitfalls when using json_decode in PHP to handle REST API responses?
- What role does data normalization play in resolving the issue described in the forum thread regarding displaying player names in separate tabs based on game categories?