What best practices should be followed when creating a PHP form for email submission?
When creating a PHP form for email submission, it is important to sanitize and validate user input to prevent malicious code injection and ensure data integrity. Additionally, use PHP's built-in mail() function to send the email securely. Finally, consider implementing CSRF protection to prevent cross-site request forgery attacks.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$to = "recipient@example.com";
$subject = "New email submission";
$message = "Email: " . $email;
$headers = "From: sender@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully";
} else {
echo "Failed to send email";
}
} else {
echo "Invalid email address";
}
}
?>
Related Questions
- What are the best practices for handling and registering namespaces when using XPath queries in PHP to access specific elements in an XML document?
- When using functions in PHP, what are the best practices for passing database connections as parameters?
- In what scenarios would it be recommended to use $_REQUEST over $_POST or $_GET in PHP programming?