Every day, approximately 361 billion emails are sent and received as part of marketing campaigns. With 4.37 billion email users reported in 2023, each user receives an average of 82.6 messages daily. Impressive, isn’t it?
To obtain the email address of a potential lead, you will need at least a simple PHP contact form on your website. An email contact form is an optimal solution if you just want to connect with your site’s visitors the easiest way possible. PHP is combined with HTML and CSS to create modern, highly interactive interfaces, whether as standalone pages or widgets that can be seamlessly integrated into the code. Leveraging an email API service will help you reliably deliver form data to a mailbox of your choice.
This guide will walk you through everything you need to know about creating a PHP contact form.
What is a PHP Email Contact Form?
A contact form is a specialized interface that can be embedded into a website or page structure. It helps users communicate with the site administration, technical support team, or other designated personnel, depending on the form’s type and placement.
Due to the simplicity of creating a contact form with PHP, this type of integration is very common among marketers collecting user data. It is also widely used by technical support teams as a primary tool for gathering feedback, addressing issues, and engaging with users.
Accordingly, if your activity is related to the listed processes, you are simply obliged to know about the specifics of creating a contact form using HTML and PHP, and additional customization. This is precisely what the following guide will help you with.
How to Create a PHP Contact Form
Our contact form will utilize various elements of HTML, PHP, and CSS, depending on the specific form you need to create:
- HTML will be used to implement the markup.
- CSS will serve to style the form, format fonts, input fields, and other elements.
- PHP is used as a back-end programming language to collect entered data and send it by email.
Creating the HTML Structure
If you are just starting to work on your first simple PHP contact form, you should not immediately look for ready-made templates, which you may need to spend a lot of time understanding and adapting to your needs.
You should start with the basics. HTML is quite easy, so it’s worth familiarizing yourself with the most basic layout rules in advance.
Here is an example of implementing a basic contact form:
<form action=”submit.php” method=”POST” id=”contact_form”>
<p class=”heading”>Contact us</p> <p>Name</p> <input type=”text” name=”name” class=”input”> <p>Email</p> <input type=”email” name=”email” class=”input”> <p>Message</p><textarea name=”message” rows=”6″ cols=”25″ class=”input”></textarea><br /> <input type=”submit” value=”Send” class=”btn_submit”> <input type=”reset” value=”Cancel” class=”btn_reset”> </form> |
The form (with some styling, which we’ll cover a bit later) will look as follows:
Not too appealing, right? Well, for formatting and styling the contact PHP form, CSS can be applied. That’s what we’ll do in the next step.
Adding CSS for Styling
To style a PHP contact form, you’ll need to add a few lines to your page’s CSS. The file is usually referenced in the head tag of the page’s HTML file. Your style definitions might look as follows:
form#contact_form { max-width:420px; margin:50px auto; }
form#contact_form input { color:black; font-family: Helvetica, Arial, sans-serif; font-weight:500; font-size: 18px; border-radius: 5px; line-height: 22px; background-color: transparent; border:2px solid #CC6666; } form#contact_form input:focus { border:2px solid #CC4949; } form#contact_form textarea { height: 150px; line-height: 150%; resize:vertical; } form#contact_form input[type=”submit”] { background:#CC6666; } form#contact_form [type=”submit”]:hover { background:#CC4949; } |
If you don’t know how to manually work with CSS, you can use specialized tools such as PHP Jabbers, FormBuilder, and others.
Note that you should always set a unique class or id attribute for your <form> tag and make sure your css selectors for other form elements are subordinate to this attribute, otherwise you risk affecting the layout of other elements on your page, besides the contact form.
Include a checkbox for “Accept Terms and Privacy Policy”
Your contact form can (and should) include a checkbox for agreeing to the “Terms and Privacy Policy.” This means that the form needs to be extended with appropriate code, for example:
<input type=”checkbox” class=”terms” name=”terms” required>
<label for=”terms”>I accept the <a href=”terms.html”>Terms of Service</a> and <a href=”privacy.html”>Privacy Policy</a>.</label> |
As you can see, here we add a new form item with a checkbox and an active link to the privacy policy page. This means the user has the opportunity to review the terms of the agreement before accepting them.
Incorporate Google reCAPTCHA
It also makes sense to create a PHP contact form with anti-spam protection, using Google reCAPTCHA. This helps filter out bots and provides additional confirmation that the user intentionally interacted with the form. To start, you need to create an account via the link and complete the form following the prompts. Here, you should also select the script version supported by your system.
You will receive a site key and a secret key, which will be used for validating the submitted form. The PHP validation code for your server might look like this:
<?php
$errors = []; $errorMessage = ”; $secret = ‘your reCAPTCHA secret key’; if (!empty($_POST)) { $recaptchaResponse = $_POST[‘g-recaptcha-response’]; $recaptchaUrl = “https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$recaptchaResponse}”; $verify = json_decode(file_get_contents($recaptchaUrl)); if (!$verify->success) { $errors[] = ‘Recaptcha failed’; } } |
Essentially, the above is enough for the initial setup of your contact form. Now insert the HTML code into your page and add the style definitions to your main CSS file. Next, you should ensure that the user data is actually processed and isn’t lost permanently. This will be our focus moving forward.
Methods for Collecting Data from a PHP Contact Form
Let’s assume you’ve created a contact form and placed it on your website. Great. But are you sure that the data entered by users will reach your server for further processing? To ensure this, look at the two attributes of your <form> tag, namely, action and method.
The POST method is used to transmit entered information to submit.php, mentioned in the action attribute. After pressing “Send,” the entered data will be sent to submit.php for subsequent saving and processing according to the algorithm.
Techniques for Validating and Verifying Data from a Contact Form
You can include additional validation of user-entered data even before submitting the data, by using JavaScript. For instance, for type=”email” you can use a regex pattern “[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$” to process only standard email address formats.
If you have the necessary skills, you can create the appropriate scripts yourself. However, sometimes there’s no need to reinvent the wheel, as reliable solutions already exist, such as:
<script src=”//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js”></script> |
The above line should be included in your page to load a ready-made verification code library from a network repository.
Here’s what your validation script may look like:
<script>
const constraints = { name: { presence: { allowEmpty: false } }, email: { presence: { allowEmpty: false }, email: true }, message: { presence: { allowEmpty: false } } }; const form = document.getElementById(‘contact-form’); form.addEventListener(‘submit’, function (event) { const formValues = { name: form.elements.name.value, email: form.elements.email.value, message: form.elements.message.value }; const errors = validate(formValues, constraints); if (errors) { event.preventDefault(); const errorMessage = Object .values(errors) .map(function (fieldValues) { return fieldValues.join(‘, ‘)}) .join(“\n”); alert(errorMessage); } }, false); </script> |
Validation can also be configured on the back-end side. This is how you can set up the validation process on the server side, using PHP:
<?php
$errors = []; if (!empty($_POST)) { $name = $_POST[‘name’]; $email = $_POST[’email’]; $message = $_POST[‘message’];
if (empty($name)) { $errors[] = ‘Name is empty’; } if (empty($email)) { $errors[] = ‘Email is empty’; } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = ‘Email is invalid’; } if (empty($message)) { $errors[] = ‘Message is empty’; } } |
Sending Emails with Unione
The standard method for sending emails from PHP is the PHP mail() function. It has several significant limitations, so it is not recommended for use. As an alternative option, we will use the PHP Mailer library. You may also opt for an email SMTP service, such as UniOne, whose features are optimal for sending emails from a contact form.
Here’s a code example:
<?php
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require ‘vendor/autoload.php’; // Adjust based on your installation method $mail = new PHPMailer(true); // Enable exceptions // SMTP Configuration $mail->isSMTP(); $mail->Host = smtp.us1.unione.io or smtp.eu1.unione.io’; // Your SMTP server $mail->SMTPAuth = true; $mail->Username = ‘your_username’; // Your UniOne username $mail->Password = ‘your_password’; // Your UniOne password $mail->SMTPSecure = ‘tls’; $mail->Port = 587; // Sender and recipient settings $mail->setFrom(‘from@example.com’, ‘From Name’); $mail->addAddress(‘recipient@example.com’, ‘Recipient Name’); // Sending plain text email $mail->isHTML(false); // Set email format to plain text $mail->Subject = ‘Your Subject Here’; $mail->Body = ‘This is the plain text message body’; // Send the email if(!$mail->send()){ echo ‘Message could not be sent. Mailer Error: ‘ . $mail->ErrorInfo; } else { echo ‘Message has been sent’; } |
Conclusions
At first glance, creating a contact form may seem like a challenging and complex task. Indeed, certain difficulties will arise, especially during the early stages, but you will easily overcome them by simply following the advice in this guide.
Also, remember that the built-in mail() function might not be sufficient for your PHP contact forms, so it’s better to use specialized libraries and SMTP services like UniOne.
Try the capabilities of UniOne by building your first contact PHP form!