Home >Backend Development >PHP Tutorial >How to Send Emails from an HTML Form Using PHP on the Same Page?
Send Email with PHP from HTML Form on Submit with the Same Script
This script allows you to send an email from an HTML form using PHP without switching to a different page or script.
Code Explanation:
<?php if (isset($_POST['submit'])) { $to = $_POST['email']; $from = "[email protected]"; $headers = "From:" . $from; $message = "This is a message from an HTML form.\n\n"; foreach ($_POST as $field => $value) { $message .= ucfirst($field) . ": " . $value . "\n"; } if (mail($to, "Message from HTML Form", $message, $headers)) { echo "Mail Sent."; } else { echo "Failed to send mail."; } } ?> <!DOCTYPE html> <html> <head> <title>HTML Form</title> </head> <body> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> <label for="name">Name:</label> <input type="text">
In this code, the mail_handler.php script is part of the HTML form. When the form is submitted, the data is processed by the same script, and an email is sent using the mail() function. This keeps the user on the same page and provides a seamless experience.
Additional Information:
The above is the detailed content of How to Send Emails from an HTML Form Using PHP on the Same Page?. For more information, please follow other related articles on the PHP Chinese website!