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> |
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"> |
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 { |
Here's what the form should look like as a result:
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"> |
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"> |
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,}$/; |
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)) { |
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); |
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 |
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 |
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 |
С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.