If you are looking to create a website that allows users to contact you or your business, creating a contact form is a necessary feature. In this article, we will guide you through the process of creating a contact form in PHP. We will go through the code step by step, and explain each section in detail so that even beginners can follow along.
Step 1: Create the HTML Form
To begin, we will create the HTML form that will be used to gather user input. This is part of the form that the user will interact with, and it will be displayed in the user’s web browser.
<form method="post" action="process.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<input type="submit" value="Submit">
</form>
This code will create a basic form with fields for the user’s name, email address, subject, and message. The required
attribute is included on each field to ensure that the user fills out all fields before submitting the form. The action
attribute on the form element specifies the PHP script that will process the form data.
Step 2: Create the PHP Script
Next, we will create the PHP script that will receive the form data and process it. This script will be executed on the server-side and will handle the form submission.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
// Email destination
$to = "youremail@example.com";
// Email subject
$email_subject = "New contact form submission: $subject";
// Email headers
$headers = "From: $name <$email>" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
// Email message
$email_message = "Name: $name\n" .
"Email: $email\n" .
"Subject: $subject\n\n" .
"Message:\n$message";
// Send the email
mail($to, $email_subject, $email_message, $headers);
}
?>
This code checks if the form was submitted using the POST method, and then retrieves the form data using the $_POST
superglobal. It then sets the destination email address, subject, and headers. Finally, it uses the mail()
function to send the email.
Step 3: Add Form Validation
Form validation is an important step to ensure that the user inputs the correct data in the correct format. We will add validation to the PHP script to check that the user’s email address is valid.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email address");
}
// Email destination
$to = "youremail@example.com";
// Email subject
$email_subject = "New contact form submission: $subject";
// Email headers
$headers = "From: $name <$email>" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
// Email message
$email_message = "Name: $name\n" .
"Email: $email\n" .
"Subject: $subject\n\n" .
"Message:\n$message";
// Send the email
mail($to, $email_subject, $email_message, $headers);
}
This code uses the `filter_var()` function to check if the user’s email address is valid. If the email address is invalid, the script will halt execution and display an error message.
Step 4: Add Form Security
Form security is important to prevent spam and malicious attacks. We will add a CAPTCHA to the form to ensure that the user is a human.
<form method="post" action="process.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<input type="submit" value="Submit">
</form>
This code adds a div element with the class g-recaptcha
. The data-sitekey
attribute is set to the site key provided by reCAPTCHA. This will display the reCAPTCHA widget in the form.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$response = $_POST["g-recaptcha-response"];
// Verify the user's response
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
"secret" => "your_secret_key",
"response" => $response
];
$options = [
"http" => [
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n",
"content" => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$json = json_decode($result);
// Check if the response is valid
if (!$json->success) {
die("Invalid reCAPTCHA response");
}
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email address");
}
// Email destination
$to = "youremail@example.com";
// Email subject
$email_subject = "New contact form submission: $subject";
// Email headers
$headers = "From: $name <$email>" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
// Email message
$email_message = "Name: $name\n" .
"Email: $email\n" .
"Subject: $subject\n\n" .
"Message:\n$message";
// Send the email
mail($to, $email_subject, $email_message, $headers);
}
?>
This code retrieves the user’s reCAPTCHA response from the form data and sends a POST request to the reCAPTCHA API to verify the response. If the response is invalid, the script will halt execution and display an error message.
Step 5: Customize the Form
Finally, we will customize the form to match your website’s design and add additional fields if necessary. You can modify the HTML and CSS to match your website’s layout, and add additional form fields to gather more information from the user.
Conclusion
Creating a contact form in PHP is a simple process, but it requires attention to detail to ensure that the form is secure and user-friendly. By following the steps in this article, you can create a functional contact form that will allow users to contact you or your business with ease.
📕 Related articles about PHP
- PHP Boolean
- The Power of AJAX PHP: A Comprehensive Guide
- Mastering PHP Constants: A Comprehensive Guide
- PHP Inheritance: What You Need to Know
- The Ultimate Guide to PHP Namespaces
- PHP Objects: A Comprehensive Guide to Object-Oriented Programming in PHP