Jinsi ya Kufungua File Kwa Usalama Baada ya Login Katika PHP
Mfano wa Code: Kufungua File Baada ya Login
1️⃣ Login ya Mtumiaji (login.php)
<?php
session_start();
$valid_user = "user1";
$valid_pass = "password123";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = $_POST['username'] ?? '';
$pass = $_POST['password'] ?? '';
if ($user === $valid_user && $pass === $valid_pass) {
$_SESSION['logged_in'] = true;
header("Location: file_access.php");
exit;
} else {
echo "Username au password sio sahihi!";
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button>Login</button>
</form>
2️⃣ Kufungua File (file_access.php)
<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header("Location: login.php");
exit;
}
// Path ya file unalotaka kufungua
$file = 'documents/example.pdf';
if (file_exists($file)) {
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo "File haipo!";
}
?>
3️⃣ Logout (logout.php)
<?php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
exit;
?>
🔗 Links Za Kujifunza Zaidi
🌐 Faulink Official Website:
https://www.faulink.com/
📘 Jifunze Web Design & Programming:
https://www.faulink.com/excel_mifumo.php
📲 Piga / WhatsApp kwa msaada wa haraka:
https://wa.me/255693118509