A contact form on your website allows visitors to get in touch with you easily. In this guide, we will show you how to create a simple PHP contact form.
Step 1: Create the HTML Form
Start by creating an HTML form to collect user input. You'll need fields for their name, email, subject, and message. Here's an example form:
Step 2: Create the PHP Script
Now, you need a PHP script to process the form data and send an email. Create a file named
process.php and add the following code:<?php
if ($_SERVER[`REQUEST_METHOD`] == `POST`) {
$name = $_POST[`name`];
$email = $_POST[`email`];
$subject = $_POST[`subject`];
$message = $_POST[`message`];
$to = `your_email@example.com`;
$headers = `From: $email`;
if (mail($to, $subject, $message, $headers)) {
echo `Message sent successfully!`;
} else {
echo `Message could not be sent.`;
}
}
?>
Step 3: Customize and Test
Customize the
$to variable with your email address. You can also enhance the form with additional features like CAPTCHA or input validation. Test the form thoroughly to ensure it works as expected.Conclusion
Creating a PHP contact form is a valuable addition to your website. It allows users to reach out to you easily, and you can process their messages using PHP.
