PHP Contact Form Tutorial with Validation and Email Submit

In this tutorial, we are going to learn how to create a contact form with PHP validation and email submit.

We have taken the front-end code from CodePen. Notice that there is no JavaScript in our code, because we have created validation rules in PHP.

There are three files in our project namely form.php, form.css, and form_process.php.

Performing form processing on the same page

The code from the ‘form_process.php’ file processes our HTML form. We are using a super global variable called $SERVER[“PHP_SELF”], which gives us the filename of the current PHP page. We are using this variable so that we can perform the form processing on the same page. The value of the 'action' attribute specifies the PHP page that needs to be called when the ‘Submit’ button is clicked.

<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post">

Including a PHP file

The following code shows how we have included the 'form_process.php' file in our 'form.php' page using the include() function.

<?php include('form_process.php'); ?>

Naming the fields and the error variables

We have named our fields with these keyword names: “name”, “email”, “phone”, “url”, and “message”. Our variables that will store the error messages are $name_error, $email_error, $phone_error, and $url_error. We need to set all these variables to an empty string so that no error message is shown when the form is being displayed.

<fieldset> <input placeholder="Your name" type="text" name="name" value="<?= $name ?>" tabindex="1" autofocus> <span class="error"><?= $name_error ?></span> </fieldset> <fieldset> <input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2"> <span class="error"><?= $email_error ?></span> </fieldset> <fieldset> <input placeholder="Your Phone Number" type="text" name="phone" value="<?= $phone ?>" tabindex="3"> <span class="error"><?= $phone_error ?></span> </fieldset> <fieldset> <input placeholder="Your Web Site starts with http://" type="text" name="url" value="<?= $url ?>" tabindex="4" > <span class="error"><?= $url_error ?></span> </fieldset> <fieldset> <textarea value="<?= $message ?>" name="message" tabindex="5"> </textarea> </fieldset>

Defining variables and setting them to empty values

We have defined the necessary variables and have set them to empty values as shown in the code below. The variables $name, $email, $phone, $message, and $url will contain name, email address, phone number, message, and website URL respectively. $success will hold the success message, and $name_error, $email_error, $phone_error, and $url_error will store the error messages.

$name_error = $email_error = $phone_error = $url_error = ""; $name = $email = $phone = $message = $url = $success = "";

Form submission with the POST method

$_SERVER["REQUEST_METHOD"] is a super global variable, where "REQUEST_METHOD" is its key. If the value of this variable is "POST", then we know that the form has been submitted with the POST method. The ‘if’ statement below checks if the form submission has been done with the POST method.

if ($_SERVER["REQUEST_METHOD"] == "POST") {

Creating a user-defined function

We have created a PHP function named test_input() that strips out unnecessary spaces and slashes, and escapes all the special HTML characters.

function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }

Data validation in PHP

You can validate data in different ways. We have used PHP functions and regular expressions to create the validation rules. The following sections explain how we have validated the name, email address, phone number, and the website URL entered through the contact form.

Name validation

First of all, we want to check if the name field is empty. If it is is empty, the following error message will be displayed: “Name is required”. This particular string will be the value of the variable $name_error. In the code below, the regular expression checks if there are only letters and white spaces in the entered name. If the user enters anything else such as a number or '@' in the name field, the following error message will be displayed: "Only letters and white space allowed".

if (empty($_POST["name"])) { $name_error = "Name is required"; } else { $name = test_input($_POST["name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $name_error = "Only letters and white space allowed"; } }

Email address validation

We need to check if the email field is empty. If it is empty, an error message will be displayed. This message will be stored in the variable $email_error. We have used a PHP function called filter_var() to validate the email address entered by the user.

if (empty($_POST["email"])) { $email_error = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $email_error = "Invalid email format"; } }

Phone number validation

We will also check if the phone field is empty. If it is empty, an appropriate error message will be shown, which will be stored in the variable $phone_error. A regular expression has been used to validate the phone number entered by the user.

if (empty($_POST["phone"])) { $phone_error = "Phone is required"; } else { $phone = test_input($_POST["phone"]); // check if e-mail address is well-formed if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)){ $phone_error = "Invalid phone number"; } }

Website URL validation

The error message for the URL is stored in the variable $url_error. A regular expression validates the website URL entered through the contact form. Examine the following code to understand how we have performed the URL validation using PHP.

if (empty($_POST["url"])) { $url_error = ""; } else { $url = test_input($_POST["url"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$url)) { $url_error = "Invalid URL"; } }

Styling the error messages

Let's add a class called error inside ‘form.css’ and set the color to red, making all error messages display red colored text.

.error { color: red; }

Saving all the form data in a string variable

We have created a variable named $message_body and have set it to empty as shown in the code below. Then we have unset $_POST['submit']. All the keys and values are obtained from the associative array $POST[] and are saved in the string variable $message_body using a foreach loop. So $message_body contains all the form data entered by the user. For example, if the user enters the following data: “John”, “john541@gmail.com”, “7865432456”, “http://www.john-site.com”, and “This is a message”, then the value of the variable $message_body will be: “name: John email: john541@gmail.com phone: 7865432456 url: http://www.john-site.com message: This is a message”

//if all the errors are empty, only then send the message if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '') { $message_body = ''; unset($_POST['submit']); foreach ($_POST as $key => $value) { $message_body .= "$key: $value\n"; } }

Configuring the php.ini file

If you are on a local host, search for “SMTP” in the php.ini file. You have to make sure that the values of SMTP, smtp_port and sendmail_from are correct. Otherwise, the mail() function will not work. The screenshot below shows how we have configured the php.ini file.

Apache restart

You need to restart the Apache service if you want to be able to send emails using the mail() function. Simply search for “Services” on your Windows OS. Then find the Apache service from the list of services and restart it.

The mail() function

The variable $to stores the email address of the recipient while the variable $subject holds the subject of the mail. The mail() function takes three parameters: $to, $subject, and $message_body. If the mail is successfully sent, the following success message is displayed: “Message sent, thank you for contacting us!”. The success message is stored in the variable $success. We need to reset all of our field values to empty string after the form has been submitted.

//COX SMTP: smtp.west.cox.net, PORT: 25 (php.ini) $to = 'vladi@clevertechie.com'; $subject = 'Contact Form Submit'; if (mail($to, $subject, $message_body)){ $success = "Message sent, thank you for contacting us!"; //reset form values to empty strings $name = $email = $phone = $message = $url = ''; }

Styling the success message

Let's add a class called ‘success’ inside form.css and modify the style of the success message.

.success { color: #ff9966; text-align: center; font-weight: bold; font-size: 14px; }

Testing

Let’s send a test message to see if our ‘Contact Form’ application works properly. All the fields need to be filled out properly. As shown in the screenshot below, we have entered a name, an email address, a phone number, a website URL and a message on the form

After clicking ‘Submit’, as you can see in the screenshot below, we are getting the message “Message sent, thank you for contacting us!”. And all the fields have been reset to empty string.

The below screenshot shows that I have received the message in my Outlook inbox.

We have tested our application and have seen that it works properly. This tutorial demonstrated how to create a contact form with PHP validation and email submit. I hope you enjoyed this tutorial.