Why Every Website Needs a Contact Form
A contact form is one of the most essential features of any website. It allows visitors to communicate with you directly without exposing your email address to spam bots. In this step-by-step guide, we'll build a simple, clean, and secure contact form using HTML for the structure and PHP for processing the data and sending an email.
Part 1: The HTML Form Structure
First, we need to create the form itself. This is the part your users will see and interact with. We'll use standard HTML5 form elements. Create a file named contact.php
and add the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Us</title>
<!-- You can link your main stylesheet here -->
<style>
body { font-family: sans-serif; padding: 20px; background-color: #f4f4f4; }
.container { max-width: 600px; margin: auto; background: #fff; padding: 20px; border-radius: 8px; }
input, textarea, button { width: 100%; padding: 10px; margin-bottom: 10px; border-radius: 4px; border: 1px solid #ddd; }
.alert { padding: 15px; margin-bottom: 20px; border-radius: 4px; }
.alert-success { color: #155724; background-color: #d4edda; border-color: #c3e6cb; }
.alert-danger { color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; }
</style>
</head>
<body>
<div class="container">
<h2>Contact Us</h2>
<?php
session_start();
if (isset($_SESSION['form_status'])):
?>
<div class="alert <?php echo $_SESSION['form_status']['success'] ? 'alert-success' : 'alert-danger'; ?>">
<?php
echo $_SESSION['form_status']['message'];
unset($_SESSION['form_status']);
?>
</div>
<?php endif; ?>
<form action="submit_contact.php" method="POST">
<label for="name">Your Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Your Email:</label>
<input type="email" id="email" name="email" required>
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject" required>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="5" required></textarea>
<button type="submit">Send Message</button>
</form>
</div>
</body>
</html>
Key points: The action="submit_contact.php"
attribute tells the form where to send the data, and method="POST"
specifies the HTTP method to use. Each input has a name
, which is crucial for PHP to identify the data.
Part 2: The PHP Processing Script
This is where the magic happens. When the user submits the form, the data is sent to this script. Create a new file called submit_contact.php
. This script will validate the data, sanitize it for security, and send it as an email.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 1. Sanitize and Validate Inputs
$name = trim(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL));
$subject = trim(filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING));
$message = trim(filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING));
// Simple validation
if (empty($name) || empty($subject) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set an error message and redirect back
$_SESSION['form_status'] = [
'success' => false,
'message' => 'Please fill out all fields correctly.'
];
header('Location: contact.php');
exit;
}
// 2. Set Up Email
$to = "your-email@yourwebsite.com"; // <-- IMPORTANT: Change this to your email address!
$headers = "From: " . $name . " <" . $email . ">" . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n";
$email_body = "You have received a new message from your website contact form.\n\n";
$email_body .= "Here are the details:\n\n";
$email_body .= "Name: " . $name . "\n";
$email_body .= "Email: " . $email . "\n";
$email_body .= "Subject: " . $subject . "\n";
$email_body .= "Message:\n" . $message . "\n";
// 3. Send the Email
if (mail($to, "New Message: " . $subject, $email_body, $headers)) {
// Set a success message
$_SESSION['form_status'] = [
'success' => true,
'message' => 'Thank you! Your message has been sent successfully.'
];
} else {
// Set a failure message
$_SESSION['form_status'] = [
'success' => false,
'message' => 'Oops! Something went wrong and we couldn\'t send your message.'
];
}
// Redirect back to the contact page
header('Location: contact.php');
exit;
} else {
// If not a POST request, redirect to the form page.
header('Location: contact.php');
exit;
}
?>
Security Focus: Validation and Sanitization
Never trust user input. We use trim()
to remove whitespace, and filter_input()
with sanitization flags (FILTER_SANITIZE_STRING
, FILTER_SANITIZE_EMAIL
) to strip out potentially malicious characters. This is a crucial step in preventing Cross-Site Scripting (XSS) attacks.
Conclusion
You now have a simple, secure, and fully functional PHP contact form. From here, you can expand on it by adding more fields, implementing CAPTCHA for spam protection, or using AJAX to submit the form without a page reload for an even better user experience.