In this tutorial, we'll be creating a contact page with HTML, CSS, and PHP. The code will consist of an HTML form, validation, and PHP code to process the form data. We'll utilize conventional methods to implement validation and create a slick experience for the end user.

The Advanced package includes additional features and a download link to the source code.

What is a contact page used for?

When a user visits your website, they can use the contact page to contact you regarding many aspects of your website and/or business. For instance, the user could report a bug, or they could give you unbiased feedback, whether their intentions are good or not.

In addition, the contact page can help you with marketing opportunities and will provide a way to communicate with your audience.

1. Getting Started

Before we start coding our contact form, we need to ensure we have a working web server and meet all the requirements below. We cannot execute PHP code without a working web server as it is a server-side programming language.

1.1. Requirements

  • Web Server — If you haven't installed a local web server solution package, I recommend you download and install XAMPP. XAMPP is an open-source web server solution package.
  • Mail Server (SMTP) — Without a working mail server, you'll be unable to receive emails that are processed using the contact form. If you're hosting your website with a provider, you shouldn't need to do anything. However, if you have your own server (dedicated/VPS), I recommend you install Postfix.

1.2. What You Will Learn in this Tutorial

  • Design a Contact Form — We'll be using CSS to design our contact form and HTML to structure our code.
  • Form Validation — Implement validation to individual elements in our form.
  • Send Mail — The PHP mail function will enable us to send mail to a specified email address.

1.3. File Structure & Setup

We will now start our web server and create the files and directories we're going to use for our contact form page.

  • Open the XAMPP Control Panel
  • Next to the Apache module, click Start
  • Next to the MySQL module, click Start
  • Navigate to XAMPPs installation directory (C:\xampp)
  • Open the htdocs directory
  • Create the following directories and files:

File Structure

\-- contactform
    |-- contact.php
    |-- style.css

The above files and directories will contain the following:

  • contact.php — This file will contain our contact form template and PHP code that will process the form.
  • style.css — The stylesheet will structure our page and make it look more appealing.

2. Designing the Contact Form with CSS

The stylesheet will structure our layout and describe how each element will display on the screen. It includes the fonts, colors, and size of the elements.

Edit the style.css file and add:

CSS
html, body, div, input, span, a, select, textarea, option, h1, h2, h3, h4, main, aside, article, section, header, p, footer, nav, pre {
    box-sizing: border-box;
    font-family: Tahoma, Geneva, sans-serif;
}
html {
    background-color: #F8F9F9;
    padding: 30px;
}
input,textarea,p {
    outline: 0;
}
h1 {
    margin: 0;
    padding: 20px;
    font-size: 22px;
    text-align: center;
    border-bottom: 1px solid #eceff2;
    color: #6a737f;
    font-weight: 600;
}
.contact {
    background-color: #fff;
    width: 500px;
    margin: 0 auto;
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,.2);
}
.contact .fields {
    position: relative;
    padding: 15px;
}
.contact input[type="text"], .contact input[type="email"] {
    display: block;
    margin-top: 15px;
    padding: 15px;
    border: 1px solid #dfe0e0;
    width: 100%;
}
.contact input[type="text"]:focus, .contact input[type="email"]:focus {
    border: 1px solid #c6c7c7;
}
.contact input[type="text"]::placeholder, 
.contact input[type="email"]::placeholder, 
.contact textarea::placeholder {
    color: #858688;
}
.contact textarea {
    resize: none;
    margin-top: 15px;
    padding: 15px;
    border: 1px solid #dfe0e0;
    width: 100%;
    height: 150px;
}
.contact textarea:focus {
    border: 1px solid #c6c7c7;
}
.contact input[type="submit"] {
    display: block;
    margin-top: 15px;
    padding: 15px;
    border: 0;
    background-color: #518acb;
    font-weight: bold;
    color: #fff;
    cursor: pointer;
    width: 100%;
}
.contact input[type="submit"]:hover {
    background-color: #3670b3;
}
.contact input[name="email"] {
    position: relative;
    display: block;
}
.contact label {
    position: relative;

}
.contact label i {
    position: absolute;
    color: #dfe2e5;
    top: 31px;
    left: 15px;
    z-index: 10;
}
.contact label i ~ input {
    padding-left: 45px !important;
}
.contact .responses {
    padding: 15px;
    margin: 0;
}

That's all we need to do for the stylesheet file. You are free to customize it to your liking.

3. Structuring the Contact Form with HTML

Now, we need to structure our page and implement the contact form and its elements.

Edit the contact.php file and add:

HTML
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,minimum-scale=1">
		<title>Contact Form</title>
		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
		<link rel="stylesheet" href="style.css">
	</head>
	<body>
		<form class="contact" method="post" action="">
			<h1>Contact Form</h1>
			<div class="fields">
				<label for="email">
					<i class="fas fa-envelope"></i>
					<input id="email" type="email" name="email" placeholder="Your Email" required>
				</label>
				<label for="name">
					<i class="fas fa-user"></i>
					<input type="text" name="name" placeholder="Your Name" required>
				<label>
				<input type="text" name="subject" placeholder="Subject" required>
				<textarea name="msg" placeholder="Message" required></textarea>
			</div>
			<input type="submit">
		</form>
	</body>
</html>

That will create our template and all the fields we'll associate with our contact form. As you can see in the head section, we have included our stylesheet file along with the FontAwesome library, which will enable us to use icons in our form.

We'll be using a POST request to process the form and therefore the form's method is set to post. As the form data will be processed in the same file, there is no need to specify the action value. Instead, we can leave it blank.

The contact form consists of the following elements:

HTML
<input id="email" type="email" name="email" placeholder="Your Email" required>

This will create the email field. We have declared the name attribute as this is what we'll use when retrieving the data with PHP, which can be retrieved with $_POST['email'].

HTML
<input type="text" name="name" placeholder="Your Name" required>

The above element will create our name field, which will be the user's real name.

HTML
<input type="text" name="subject" placeholder="Subject" required>

The above element will be our subject field, which is basically the title of the message.

HTML
<textarea name="msg" placeholder="Message" required></textarea>

Finally, we have the message field. The textarea element is different from the others we have declared as it will enable the user to write on multiple lines as opposed to just one.

Have you noticed how we have specified the required attribute on all our form elements? That's because the browser will validate the form before submission, which can help prevent multiple submissions to our server.

If we navigate to our new file in our browser, the contact form should resemble the following:

http://localhost/contactform/contact.php
PHP Contact Form

That's all we need to do for this part. We have designed and structured our contact form. Next, we'll start coding the PHP aspect.

4. Processing the Contact Form with PHP

We can finally start coding our contact form with PHP. In this section, we'll validate the form fields and send mail directly to an email address.

Edit the contact.php file and add the following code at the very top, before the template code:

PHP
<?php
// Output messages
$responses = [];
// Check if the form was submitted
if (isset($_POST['email'], $_POST['subject'], $_POST['name'], $_POST['msg'])) {
	// Validate email adress
	if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
		$responses[] = 'Email is not valid!';
	}
	// Make sure the form fields are not empty
	if (empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['name']) || empty($_POST['msg'])) {
		$responses[] = 'Please complete all fields!';
	} 
	// If there are no errors
	if (!$responses) {
		// Where to send the mail? It should be your email address
		$to      = 'contact@example.com';
		// Send mail from which email address?
		$from = 'noreply@example.com';
		// Mail subject
		$subject = $_POST['subject'];
		// Mail message
		$message = $_POST['msg'];
		// Mail headers
		$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $_POST['email'] . "\r\n" . 'X-Mailer: PHP/' . phpversion();
		// Try to send the mail
		if (mail($to, $subject, $message, $headers)) {
			// Success
			$responses[] = 'Message sent!';		
		} else {
			// Fail
			$responses[] = 'Message could not be sent! Please check your mail server settings!';
		}
	}
}
?>

First, we declare a variable that will output all the responses in our form, whether it will be an incorrect email response or something else.

Subsequently, we check if the form was submitted by checking if the post variables exist, which is what the isset() function will do for us.

Finally, if there are no validation errors, the code will try to send the mail to the specified email address. Make sure to update the $to variable to reflect your own address.

Now, we need to add the responses variable to our form. Find the following line:

HTML
<input type="submit">

Add above:

PHP
<?php if ($responses): ?>
<p class="responses"><?php echo implode('<br>', $responses); ?></p>
<?php endif; ?>

That's basically all we need to do to create a contact form. If you encounter a mail server error, you must verify your mail server settings and ensure they're correct.

PHP Tip The implode() function will convert all array elements to a formatted string. The first parameter is the separator.

For client-side validation, consider implementing the pattern attribute. It will definitely reduce the load on the server when validating the form.

Conclusion

Congratulations! You've successfully created a contact form with HTML, CSS, and PHP. What next? Consider implementing your own validation and extending the contact form to support more fields, such as category, priority, and so on.

Consider sharing the article on social websites if you've found it helpful, and drop a comment below. We greatly appreciate the support.

Enjoy coding, and thank you for reading!