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
- What role does the output_buffering setting in php.ini play in preventing the "headers already sent by" error in PHP?
- What are the advantages of using absolute paths and URLs in PHP over relative paths when including files from different directories?
- Are there any existing PHP scripts or tools that can help with automatically adding a protective loop to music files to prevent copying?