A PHP contact form is a web form that allows users to submit messages to a website owner or administrator. The form typically includes fields for the user’s name, email address, subject, message, and sometimes additional information.
Here’s an example of how to create a simple PHP contact form:
- Create a new PHP file on your server called “contact-form.php”.
- In the file, add the following HTML code to create the contact form:
<form method="post" action="process-form.php"> <label for="name">Name:</label> <input type="text" name="name" id="name" required> <br> <label for="email">Email:</label> <input type="email" name="email" id="email" required> <br> <label for="subject">Subject:</label> <input type="text" name="subject" id="subject" required> <br> <label for="message">Message:</label> <textarea name="message" id="message" required></textarea> <br> <button type="submit">Submit</button> </form>
- In the same directory, create a new PHP file called “process-form.php”.
- In the “process-form.php” file, add the following PHP code to handle the form submission:
<?php // Get the form data $name = $_POST['name']; $email = $_POST['email']; $subject = $_POST['subject']; $message = $_POST['message']; // Set the recipient email address $to = 'firstname.lastname@example.org'; // Set the email subject $email_subject = 'New Contact Form Submission: ' . $subject; // Set the email message $email_message = 'Name: ' . $name . "\n"; $email_message .= 'Email: ' . $email . "\n"; $email_message .= 'Subject: ' . $subject . "\n"; $email_message .= 'Message: ' . $message . "\n"; // Send the email mail($to, $email_subject, $email_message); // Redirect the user back to the contact form page header('Location: contact-form.php?status=success'); ?>
- In the “process-form.php” file, be sure to replace “email@example.com” with your actual email address.
- Save both files to your server.
- Test the contact form by visiting the “contact-form.php” page on your website, filling out the form, and submitting it. You should receive an email with the message content.
Note that this is just a simple example of a PHP contact form. There are many other features you can add, such as form validation, CAPTCHA, and more.