Having a contact form on your website is essential for allowing your visitors to get in touch with you easily and securely. With a simple contact form, you can collect important information from your visitors, such as their names, email addresses, and message, and respond to them in a timely manner.
In this tutorial, I'll show you how to create a functional contact form using HTML, style it with CSS to match your website's design, and process the form data securely using PHP. By following the steps in this tutorial, you'll be able to create a custom contact form that meets your website's specific needs and provides a seamless user experience for your visitors.
Prerequisites
To follow along with this tutorial, you'll need a web server with PHP installed. If you're not sure how to set this up, you can check out XAMPP, MAMP, or How to Install Apache, PHP, and MySQL on Linux Mint for an easy-to-use local server.
Step 1: Creating the HTML Form
The first step is to create the HTML form that will allow users to enter their name, email address, subject, and message. Here's an example of what the HTML code could look like:
<!DOCTYPE html> <html> <head> <title>Simple Contact Form</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <h1>Simple Contact Form</h1> <form method="post" action="process_form.php"> <label for="name">Name:</label> <input type="text" name="name" id="name" required> <label for="email">Email:</label> <input type="email" name="email" id="email" required> <label for="subject">Subject:</label> <input type="text" name="subject" id="subject" required> <label for="message">Message:</label> <textarea name="message" id="message" required></textarea> <input type="submit" value="Send"> </form> </body> </html>
As you can see, we've included a CSS file (style.css) in the head of the HTML document. We'll be using this file to style the form in the next step.
Note that we've also set the method attribute of the form element to “post” and the action attribute to “process_form.php“. This tells the form to send the data to a PHP script (process_form.php) when the user submits the form.
Step 2: Styling the Form with CSS
Next, we'll be adding some CSS to make the form look nicer. Here's an example of what the CSS code could look like in style.css:
body { font-family: Arial, sans-serif; background-color: #f7f7f7; } h1 { text-align: center; margin-top: 50px; } form { width: 80%; margin: 0 auto; background-color: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } label { display: block; margin-bottom: 10px; } input[type="text"], input[type="email"], textarea { width: 100%; padding: 10px; border: 2px solid #ccc; border-radius: 5px; margin-bottom: 20px; font-size: 16px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } textarea { height: 140px; } input[type="submit"] { background-color: #4caf50; color: #fff; border: none; padding: 10px 20px; border-radius: 5px; font-size: 16px; cursor: pointer; width: 100%; } input[type="submit"]:hover { background-color: #3e8e41; }
In this CSS code, we're styling the body to have a light gray background color and using Arial font for all text. We've also centered the h1 element and added some margin to the top.
The form element is styled to have a white background color, padding, and a border radius to create a nice rounded edge. Additionally, we've added a box shadow to create depth and dimension.
The label element is styled to have a block display and a margin-bottom of 10 pixels to provide some space between the label and the input field.
The input and textarea elements are styled to have a width of 100%, a padding of 10 pixels, a border of 2 pixels solid color, a border radius of 5 pixels, and a margin-bottom of 20 pixels. Finally, we've styled the input[type=”submit”] element to have a green background color, white text color, and a few other properties to make it look like a button.
Step 3: Processing the Form Data with PHP
Now that we have our form created and styled, we need to process the form data using PHP. Here's an example of what the PHP code could look like:
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Get the form fields and remove whitespace $name = strip_tags(trim($_POST["name"])); $name = str_replace(array("\r", "\n"), array(" ", " "), $name); $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL); $subject = strip_tags(trim($_POST["subject"])); $subject = str_replace(array("\r", "\n"), array(" ", " "), $subject); $message = trim($_POST["message"]); // Check that all fields are filled if (empty($name) || empty($subject) || empty($message) || empty($email)) { http_response_code(400); echo "Oops! There was a problem with your submission. Please complete the form and try again."; exit; } // Validate email if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { http_response_code(400); echo "Oops! There was a problem with your submission. Please enter a valid email address and try again."; exit; } // Set the recipient email address $recipient = "youremail@example.com"; // Set the email subject $email_subject = "$subject - New Form Submission from $name"; // Build the email content $email_content = "Name: $name\n"; $email_content .= "Email: $email\n\n"; $email_content .= "Subject: $subject\n\n"; $email_content .= "Message:\n$message\n"; // Build the email headers $email_headers = "From: $name <$email>"; // Send the email if (mail($recipient, $email_subject, $email_content, $email_headers)) { http_response_code(200); echo "Thank You! Your message has been sent."; } else { http_response_code(500); echo "Oops! Something went wrong and we couldn't send your message."; } } else { // Not a POST request, set a 403 (forbidden) response code http_response_code(403); echo "There was a problem with your submission, please try again."; } ?>
Set the $recipient variable to the email address where you want the form submissions to be sent. For example, $recipient = “youremail@example.com”;.
In this PHP code, we first check that the form was submitted using the $_SERVER[“REQUEST_METHOD”] variable. We then get the form fields and remove any whitespace using strip_tags() and str_replace(). We also sanitize the email address using filter_var().
Next, we check that all fields are filled using empty(). If any field is empty, we return an error message with a 400 (bad request) response code.
We then validate the email address using filter_var() and return an error message with a 400 (bad request) response code if it's not valid.
After validating the form data, we set the recipient's email address, email subject, email content, and email headers. We then use the mail() function to send the email.
If the email is sent successfully, we return a success message with a 200 (OK) response code. If there's an error sending the email, we return an error message with a 500 (internal server error) response code.
Conclusion
In this tutorial, we've learned how to create a simple contact form using HTML, style it with CSS, and process the form data securely using PHP. By following the steps in this tutorial, you can easily create a functional contact form for your website that allows your visitors to get in touch with you easily and securely.
Remember to always validate and sanitize user input to prevent security vulnerabilities, such as SQL injection or cross-site scripting attacks. Additionally, be sure to test your contact form thoroughly to ensure that it's working as intended.
With this knowledge, you can continue to expand and customize your contact form as needed to fit your website's specific requirements.