Jinsi ya Kutengeneza Contact Form na Email Integration
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:
π https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, email handling, na secure web application development.