What are the best practices for handling email addresses and message bodies in PHP contact forms to ensure proper delivery?
When handling email addresses in PHP contact forms, it is important to validate the email address before sending the message to ensure proper delivery. Additionally, it is good practice to sanitize the message body to prevent any malicious code from being injected. By following these best practices, you can improve the reliability and security of your contact form.
// Validate email address
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = $_POST['email'];
} else {
// Handle invalid email address
exit('Invalid email address');
}
// Sanitize message body
$message_body = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Send email
$to = 'recipient@example.com';
$subject = 'Contact Form Submission';
$message = "From: $email\n\n$message_body";
mail($to, $subject, $message);
Related Questions
- How does the preg_match function differ from the ereg function in terms of validating email addresses in PHP?
- What are the benefits and drawbacks of using WordPress with plugins for managing shop reviews compared to other CMS platforms like Typo, Drupal, or Joomla?
- What are the potential reasons for a file not being uploaded successfully using ftp_put in PHP?