Q > I want to send an email with PHP from an HTML form, using the same script that displays the form.
A > To achieve this, consider the following solution:
PHP Code:
if (isset($_POST['submit'])) { $to = $_POST['email']; $subject = $_POST['name']; $message = getRequestURI(); $from = "[email protected]"; $headers = "From:" . $from; if (mail($to, $subject, $message, $headers)) { echo "Mail sent."; } else { echo "Failed to send mail."; } }
HTML Form:
<form method="post"> <label>Name:</label> <input type="text" name="name"> <label>Email:</label> <input type="email" name="email"> <input type="submit" name="submit" value="Send"> </form>
In this code, when the form is submitted, the PHP script is executed. It retrieves the submitted information, crafts the email, and sends it using the mail() function. The result is displayed on the same page.
The above is the detailed content of How to Send an Email with PHP from an HTML Form Using the Same Script?. For more information, please follow other related articles on the PHP Chinese website!