How does the mail() function in PHP work for sending emails from a form?
The mail() function in PHP allows you to send emails from a form by specifying the recipient's email address, subject, message, and optional additional headers. To use the mail() function, you need to have a working mail server set up on your server or use a third-party email service. Make sure to sanitize and validate user input before using it in the mail() function to prevent injection attacks.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$to = "recipient@example.com";
$subject = $_POST["subject"];
$message = $_POST["message"];
$headers = "From: " . $_POST["email"];
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}
}
?>
Related questions
-
security session variables POST values
-
web hosting PHP MySQL
-
JavaScript form submission security concerns