To create a simple PHP web page form that sends an email with the submitted data, you can follow these steps. This example will provide you with a basic HTML form and the corresponding PHP script for processing the form data and sending the email.
Step 1: Create the HTML Form
Create an HTML file (e.g., contact_form.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="send_email.php" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" required></textarea><br><br>
<button type="submit">Send</button>
</form>
</body>
</html>
Step 2: Create the PHP Script to Send Email
Create a PHP file (e.g., send_email.php) to process the form submission:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize form data
$name = htmlspecialchars(strip_tags(trim($_POST['name'])));
$email = htmlspecialchars(strip_tags(trim($_POST['email'])));
$message = htmlspecialchars(strip_tags(trim($_POST['message'])));
// Set the recipient email address
$to = 'recipient@example.com'; // Change this to your email address
$subject = 'New Contact Form Submission';
// Construct the email body
$email_body = "Name: $name\n";
$email_body .= "Email: $email\n";
$email_body .= "Message:\n$message\n";
// Set the email headers
$headers = "From: $name <$email>\r\n";
$headers .= "Reply-To: $email\r\n";
// Execute the mail function
if (mail($to, $subject, $email_body, $headers)) {
echo "Email sent successfully!";
} else {
echo "Email sending failed.";
}
} else {
// If the form was not submitted correctly, redirect back to the form
header("Location: contact_form.html");
exit();
}
?>
Step 3: Test the Form
- Upload Files: Upload both
contact_form.html and send_email.php to your web server.
- Open the Form: Navigate to
contact_form.html in your web browser.
- Fill in the Form: Complete the form and submit it.
- Check Your Email: You should receive an email with the form submission.
Important Notes
- Email Function: The
mail() function works if your server is properly configured to send emails. If you're using a local server (like XAMPP or WAMP), you might need to configure SMTP settings.
- Validation: In a production environment, you should ensure to add server-side validation for form inputs.
- Security: Always sanitize and validate user inputs to prevent email header injection and XSS attacks.
- More Features: Consider using libraries like PHPMailer or SwiftMailer for more robust email functionalities, such as HTML emails, attachments, etc.