How can PHP be used to send email notifications or confirmations to users after submitting a form on a website?
To send email notifications or confirmations to users after submitting a form on a website, you can use the PHP `mail()` function. This function allows you to send an email from your server to the specified recipient email address. You can customize the email content, subject, and sender information within the function.
<?php
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Set recipient email address
$to = 'recipient@example.com';
// Set email subject
$subject = 'Form Submission Confirmation';
// Compose email message
$body = "Hello $name, \n\nThank you for submitting the form. We have received your message: \n$message";
// Set sender email address
$from = 'sender@example.com';
// Send email
$mail = mail($to, $subject, $body, "From: $from");
// Check if email was sent successfully
if ($mail) {
echo 'Email sent successfully';
} else {
echo 'Email sending failed';
}
?>
Related Questions
- What are some best practices for selecting and outputting specific files in PHP, such as using a new DIV for each file content?
- In what scenarios should arrays be preferred over switch statements in PHP functions?
- What potential security risks should be considered when updating database records based on user input in PHP?