PHP, Email, & Contact Form: Best Practices for Success

PHP Contact Form: A Step-by-Step Guide | UniOne
Denys Romanov Denys Romanov 05 february 2025, 11:29 186
For beginners

It’s hard to imagine our world without emails, and no wonder why — they are an effective way for businesses to communicate with their audience. But before sending these emails, businesses need to know where to send them. It is a common practice to embed subscription forms on websites to collect users' data (email, name, etc.). Another widespread scenario is using a web form to communicate with site visitors.

While there are several ways to work with contact forms, one of the most popular and reliable solutions is using a PHP Email Contact Form. In this article, we’ll dive deeper into what it is under the hood and how it works.

What is a PHP Email Contact Form?

A PHP Email Contact Form is a web-based tool that allows users to send messages or inquiries via email directly from a website. The forms are built with HTML, CSS, and JavaScript for user interaction and form validation. The next step, form sending, usually requires a backend language and may also leverage an email API service for robust delivery. In our case, we will work with PHP, which is commonly used on the backend to process and send the form data as an email.

But why do you even need to send form data by email? Well, actually, in many cases, you don’t. A typical scenario involves storing the newly obtained contacts in a database (for a subscription form) or integrating your contact form with a helpdesk app. However, for the most basic (and free!) solution, you might opt to receive the feedback submitted via form by email and use email to reply. And this is the solution we’ll be discussing in this article.

How to Create a Contact Form

We will walk through a simple, step-by-step example of creating a simple contact form. Feel free to use this example as a template for your own projects.

Creating the HTML Structure

To create a contact form, start by creating the HTML Structure. Embed the form into an existing page using the <form> tag, with input fields for the name, email, message, and a submit button.

<form>
  <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="message">Message:</label>
  <textarea id="message" name="message" required></textarea>
 
  <button type="submit">Send</button>
</form>

Include a checkbox for "Accept Terms and Privacy Policy"

Most of the time, websites ask users to comply with legal requirements before submitting a form. To do so, include a checkbox that requires users to accept your terms and privacy policy. Add this markup before the <button> tag in your HTML code:

  <label class="terms-label">
    <input type="checkbox" id="terms" name="terms" required>
    I accept the
    <a href="http://yoursite/terms" target="_blank">Terms and Privacy Policy</a>
  </label>

Incorporate Google reCAPTCHA

Google reCAPTCHA is a security service that helps protect websites from spam by verifying that users are human. To add Google reCAPTCHA to your form, first sign up for a reCAPTCHA API key. Then, insert the reCAPTCHA widget within the form before the tag. Replace "your-site-key" with the actual site key provided by Google.

This setup enhances the form’s security while keeping the design simple and unobtrusive.

  <div class="g-recaptcha" data-sitekey="your-site-key"></div>

Adding CSS for Styling

And finally, let’s add CSS to our HTML Contact Form. Note that the styling must not interfere with the page’s current layout. To achieve that, add a unique id or class attribute to your form tags, and make sure your CSS selectors include this attribute.

form {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background-color: #f9f9f9;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);                                                        
box-sizing: border-box;
}

label {
display: inline-flex;
align-items: center;
margin-bottom: 12px;
}

input:not([type='checkbox']),
textarea {
width: 100%;
padding: 10px;
margin-bottom: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

button {
background-color: #4caf50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}

.terms-label {
display: flex;
align-items: center;
}

.terms-label input[type='checkbox'] {
margin-right: 10px;
}

.terms-label a {
text-decoration: none;
color: #007bff;
padding-left: 4px;
}

.terms-label a:hover {
text-decoration: underline;
}

 

 

Here's what the form should look like as a result:

PHP contact form

A basic Contact Form

Methods for Collecting Data from a Contact Form

To collect data from a contact form, you can use one of the two common methods: HTTP POST and Ajax. 

The HTTP POST method sends form data to the server when the user submits the form. Here’s what you need to add to the markup above:

<form action="submit_form.php" method="POST">
    …
</form>

 

When the form is submitted, data is sent to submit_form.php using HTTP POST, as specified by the attributes of the form tag. Your entire page will be reloaded in the process. Ajax is a more modern approach that allows you to submit the form without reloading the page, improving the user experience.

 Here’s an Ajax example using the JavaScript Fetch API:

<form id="contact-form">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br>
    <label for="message">Message:</label>
    <textarea id="message" name="message" required></textarea><br>
    <button type="submit">Submit</button>
</form>

<script>
document.getElementById('contact-form').addEventListener('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);

    fetch('submit_form.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Form submitted successfully!');
        } else {
            alert('Error submitting form');
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
});
</script>

 

With the Ajax method, the form sends data asynchronously to the server, allowing the page to remain responsive. Such behavior is vital for modern applications that focus on smooth user interactions.

Techniques for Validating and Verifying Data from a Contact Form

It’s a must to validate and verify data from a contact form to ensure both accuracy and security. There’s not much sense in allowing your visitors to submit empty forms or enter random strings instead of a proper email address. Most importantly, a malicious actor could abuse your form to execute harmful code on your server.

Validation can and should be performed both on the client’s side (that is, inside the user’s browser) and on the server. The former allows checking for proper input even before the data is submitted, further improving usability, and the latter is also a must because hackers can forge form requests without using a browser. Let's cover client-side validation using JavaScript and server-side validation with PHP.

Client Side Validation with JavaScript

Client-side validation is performed inside the browser, typically using JavaScript. The validation happens before the form is submitted to the server.

A common technique is to use regular expressions to validate input fields like email addresses. For instance, you can use this regex to ensure the email follows the correct format:

const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailRegex.test(formData.get("email"))) {
    console.log("Invalid email format");
}

This validation code may be added to the Ajax example above, right before fetch(). If the form uses HTTP POST, a different approach is required. You define a separate JavaScript function validateForm() which returns true if user input is valid, or false otherwise. Then you add this function to the form tag, to be called before submit:

 

<form action="submit_form.php" method="POST" onsubmit="return validateForm(this);">

Server Side Validation with PHP

Server-side validation is most essential for security as client-side validation may be easily bypassed by malicious actors. Form security deserves a separate article, to be honest, but the most basic considerations to take into account are:

  • Never show user input on your site “as-is”. Hackers could exploit this option to break your page’s layout or run malicious JavaScript code. All user input should be sanitized with the htmlentities() function which turns any markup into harmless HTML entities.
  • An even more apocalyptic scenario may unfold if you store raw input in your database (there’s an excellent xkcd comic strip on that, btw). The proper way to avoid this is using prepared statements.

Having implemented the above, you may turn your attention to actual server-side validation. In PHP, you can validate form input using the filter_var() function:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
}

To verify if the user’s domain is alive, you can check its DNS records. Using PHP’s checkdnsrr() function, you can confirm whether the domain has valid DNS entries, indicating that the domain is active:

$domain = substr(strrchr($email, "@"), 1);
if (checkdnsrr($domain, "MX")) {
    echo "Domain is valid";
} else {
    echo "Domain not found or DNS error";
}

Send Emails from a PHP Contact Form

Sending emails from a PHP contact form is essential for communication. Its primary use is in enhancing user engagement and providing quick responses.

Below is a basic example of how to send an email with PHP. It uses a built-in mail() function which is deceptively easy to use for the programmer. It uses your site hoster’s SMTP facilities, and you should really care about how their mail server is configured. Otherwise, you may encounter delivery problems or quota restrictions, all of a sudden.

<?php
$to = "admin@example.com";
$subject = "New Contact Form Submission";
$message = "Name: " . $_POST['name'] . "\nEmail: " . $_POST['email'] . "\nMessage: " . $_POST['message'];
$headers = "From: " . $_POST['email'];

if (mail($to, $subject, $message, $headers)) {
    echo "Thank you for contacting us!";
} else {
    echo "There was an error sending your message. Please try again.";
}
?>

Using PHPMailer to Send Emails from a PHP Contact Form

PHPMailer is a popular PHP library used for sending emails. It supports explicit SMTP configuration, HTML content, and attachments, offering better error handling and security. 

Using PHPMailer to send emails from a PHP contact form is a more reliable and secure method than using the mail() function.

Here’s an example of sending an email using PHPMailer:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_email@example.com';
    $mail->Password = 'your_password';
    $mail->Port = 587;

    $mail->setFrom($_POST['email'], $_POST['name']);
    $mail->addAddress('admin@example.com');
    $mail->isHTML(true);
    $mail->Subject = 'New Contact Form Submission';
    $mail->Body    = 'Name: ' . $_POST['name'] . '<br>Email: ' . $_POST['email'] . '<br>Message: ' . $_POST['message'];

    $mail->send();
    echo 'Message sent';
} catch (Exception $e) {
    echo "Mailer Error: {$mail->ErrorInfo}";
}
?>

Sending Emails with Unione

If you’re already using an email SMTP service like UniOne to send your marketing or transactional emails, you should definitely use this option for your form mail as well. The most efficient way here would be using the ESP’s own integration library, like the UniOne Email PHP library. It integrates smoothly with PHP, enabling developers to generate rich, templated emails with variables, conditions, and loops. 

To use UniOne for sending emails, you would typically set up an email template and pass the dynamic content through the UniOne engine. 

Here’s a simple example of how to use UniOne to send an email with PHP:

<?php
require 'vendor/autoload.php';

use Unione\Unione;

$template = 'email_template.html';
$data = [
    'name' => $_POST['name'],
    'email' => $_POST['email'],
    'message' => $_POST['message']
];

$mailContent = Unione::render($template, $data);

$to = 'admin@example.com';
$subject = 'New Contact Form Submission';
$headers = 'From: ' . $_POST['email'];

if (mail($to, $subject, $mailContent, $headers)) {
    echo 'Message sent';
} else {
    echo 'Error sending message';
}
?>

Сonclusion

When implementing email functionality in a PHP contact form, it's crucial to consider best practices for security, usability, and efficiency. While traditional methods like PHP’s mail() function and PHPMailer are widely used, integrating a library like UniOne provides significant advantages. It offers a range of features, including seamless integration, scalability and strong security. Consider using UniOne to succeed in fulfilling all your email communication needs.

FAQ

What is a PHP email contact form, and why is it important?

A PHP email contact form is a web form you add to your site’s pages. It lets users submit their feedback directly to the website owner via email. This enhances customer engagement and user experience while ensuring secure, prompt inquiries. It's an essential communication tool for business and personal websites.

How do I use PHP to process contact form data?

To process contact form data with PHP, you start by collecting the data submitted through the form. Then you validate it to ensure it meets the necessary criteria. Once the data is validated, you can store it in a database for future use. Additionally, PHP can send an email to the site owner with the form details, allowing for immediate notification of new submissions.

Can I send attachments through my PHP contact form?

Yes, you can send attachments through your PHP contact form by handling file uploads. This typically requires using PHP’s $_FILES superglobal and libraries like UniOne's API library or PHPMailer.

Related Articles
Blog
For beginners
How to Recall an Email in Outlook, Gmail, and Yahoo: The Ultimate Guide
Every email user can remember a few occasions when they sent an email with missing details, typos, o
Yurii Bitko
21 may 2024, 15:2810 min
Blog
For beginners
10 Best Mailgun Alternatives For Transactional Emails
Find Mailgun alternatives for reliable and cost-effective transactional email delivery.
Valeriia Klymenko
30 august 2024, 12:1715 min
Blog
For experts
How to Configure an SMTP Server Connection?
Tutorial on SMTP configuration procedures.
Alexey Kachalov
11 january 2022, 13:053 min