Home >Backend Development >PHP Tutorial >How to Send Emails from an HTML Form Using PHP on the Same Page?

How to Send Emails from an HTML Form Using PHP on the Same Page?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 17:13:14815browse

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&#160;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 default action of a form is to POST data to itself. Specifying the action as "" or the same PHP script ensures that the data is submitted to the same page for handling.
  • The foreach loop in the code iterates over the $_POST array and constructs the body of the email message by appending each field name and its corresponding value.
  • The htmlspecialchars() function prevents Cross-Site Scripting (XSS) attacks by escaping special characters in the input.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn