Html email form php
Here is an example of how to create an HTML email form that sends data to a PHP script:
HTML Form
<form action="send_email.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea><br><br>
<input type="submit" value="Send">
</form>
PHP Script (send_email.php)
<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate the form data
if (!empty($name) &&!empty($email) &&!empty($message)) {
// Send the email
$to = "[email protected]";
$subject = "Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
mail($to, $subject, $body);
// Display a success message
echo "Thank you for contacting us!";
} else {
// Display an error message
echo "Please fill out all fields!";
}
}
?>
How it works
- The HTML form is created with input fields for name, email, and message.
- The form is submitted to the PHP script
send_email.php
using theaction
attribute. - The PHP script checks if the form has been submitted using the
$_SERVER["REQUEST_METHOD"]
variable. - If the form has been submitted, the script gets the form data using the
$_POST
superglobal array. - The script validates the form data by checking if all fields are filled out.
- If the form data is valid, the script sends an email using the
mail()
function. - The script displays a success message if the email is sent successfully.
- If the form data is invalid, the script displays an error message.
Note
- Make sure to replace
[email protected]
with the actual email address you want to receive the form submissions. - You may want to add additional validation and error handling to your PHP script.
- You can also use a library like PHPMailer to send emails with more advanced features.