Jinsi ya Kutengeneza Contact Form na Email Integration
Contact form ni muhimu kwa:
Kupata messages kutoka kwa website visitors.
Kutuma emails moja kwa moja kwa admin au support team.
Kuunda professional interaction na users.
Security considerations:
Validate na sanitize input.
Prevent email header injection.
Optionally include CSRF token kwa protection zaidi.
⚙️ 2. HTML Contact Form
<h2>Contact Us</h2>
<form action="contact.php" method="POST">
<input type="text" name="name" placeholder="Your Name" required><br><br>
<input type="email" name="email" placeholder="Your Email" required><br><br>
<input type="text" name="subject" placeholder="Subject" required><br><br>
<textarea name="message" placeholder="Your Message" rows="5" required></textarea><br><br>
<button type="submit" name="submit">Send Message</button>
</form>
💡 Maelezo:
All fields ni required.
Email input type inasaidia browser validation.
🧩 3. PHP Script ya Contact Form (contact.php)
<?php
if(isset($_POST['submit'])){
// Sanitize input
$name = htmlspecialchars(trim($_POST['name']));
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$subject = htmlspecialchars(trim($_POST['subject']));
$message = htmlspecialchars(trim($_POST['message']));
// Validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
die("❌ Invalid email address.");
}
$to = "admin@example.com"; // Email ya admin
$full_message = "Name: $name\nEmail: $email\n\nMessage:\n$message";
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($to, $subject, $full_message, $headers)){
echo "✅ Message sent successfully!";
} else {
echo "❌ Failed to send message.";
}
}
?>
💡 Maelezo:
htmlspecialchars() inazuia XSS attacks.
filter_var() inathibitisha email address.
Mail function inatumwa kwa admin.
🔑 4. Vidokezo vya Usalama
Validate inputs – prevent malicious content.
Sanitize inputs – avoid XSS.
Prevent header injection – avoid including \r or \n in email fields.
Use CSRF tokens – protect form from cross-site attacks.
Consider PHPMailer – more reliable and secure for production emails.
✅ 5. Hitimisho
Contact form na email integration inarahisisha communication na users.
PHP mail() function inaweza kutumika kwa simple form notifications.
Best practice: sanitize input, validate email, optionally use PHPMailer, add CSRF protection.
🔗 Tembelea:
Kwa mafunzo zaidi ya PHP, email handling, na secure web application development.
🚀 Unahitaji mfumo au website ya biashara?
Chagua huduma hapa chini kisha mteja bofya moja kwa moja kwenda kwenye ukurasa wa huduma au kuwasiliana nasi kwa WhatsApp.