May 10, 2026 1 min read

PHP Login System Tutorial 2026 — Jinsi ya Kutengeneza Secure Login kwa PHP PDO na MySQL

Jifunze kutengeneza PHP Login System kwa kutumia PHP PDO na MySQL. Login system salama yenye password hashing, session security, logout na protected pages.

PHP Login System ni Nini?

PHP Login System ni mfumo unaoruhusu user kuingia kwenye website au application kwa kutumia username/email na password.

Mfumo huu hutumika kwenye:

Admin Panel
School System
Accounting System
Farm Management System
POS System
Inventory System
Hospital System

Kwa tutorials zaidi:
https://faulink.com

STEP 1 — Tengeneza Database
CREATE DATABASE php_login_system;

USE php_login_system;
STEP 2 — Tengeneza Users Table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
full_name VARCHAR(150) NOT NULL,
username VARCHAR(100) NOT NULL UNIQUE,
email VARCHAR(150) UNIQUE,
password VARCHAR(255) NOT NULL,
status ENUM('active','inactive') DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
STEP 3 — Database Connection

config.php

<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}

$host = "localhost";
$dbname = "php_login_system";
$user = "root";
$pass = "";

try {
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]
);
} catch (PDOException $e) {
die("Database Connection Failed");
}

function clean($data) {
return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

function isLoggedIn() {
return isset($_SESSION['user_id']);
}

function requireLogin() {
if (!isLoggedIn()) {
header("Location: index.php");
exit;
}
}

function logout() {
session_unset();
session_destroy();
header("Location: index.php");
exit;
}
?>
STEP 4 — Register User

register.php

<?php
require_once 'config.php';

$message = '';

if (isset($_POST['register'])) {
$full_name = clean($_POST['full_name']);
$username = clean($_POST['username']);
$email = clean($_POST['email']);
$password = $_POST['password'];

if ($full_name == '' || $username == '' || $password == '') {
$message = "Please fill all required fields.";
} else {
$check = $pdo->prepare("
SELECT id
FROM users
WHERE username = ? OR email = ?
LIMIT 1
");
$check->execute([$username, $email]);

if ($check->fetch()) {
$message = "Username or email already exists.";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

$stmt = $pdo->prepare("
INSERT INTO users
(full_name, username, email, password)
VALUES (?, ?, ?, ?)
");

$stmt->execute([
$full_name,
$username,
$email,
$hashedPassword
]);

$message = "Account created successfully.";
}
}
}
?>

<form method="POST">
<input type="text" name="full_name" placeholder="Full Name" required>
<input type="text" name="username" placeholder="Username" required>
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password" required>

<button type="submit" name="register">
Register
</button>
</form>

<p><?= $message; ?></p>
STEP 5 — Login User

index.php

<?php
require_once 'config.php';

if (isset($_GET['logout'])) {
logout();
}

$error = '';

if (isset($_POST['login'])) {
$username = clean($_POST['username']);
$password = $_POST['password'];

$stmt = $pdo->prepare("
SELECT *
FROM users
WHERE username = ?
AND status = 'active'
LIMIT 1
");

$stmt->execute([$username]);
$user = $stmt->fetch();

if ($user && password_verify($password, $user['password'])) {
session_regenerate_id(true);

$_SESSION['user_id'] = $user['id'];
$_SESSION['full_name'] = $user['full_name'];
$_SESSION['username'] = $user['username'];

header("Location: dashboard.php");
exit;
} else {
$error = "Invalid username or password.";
}
}
?>

<form method="POST">
<?php if ($error): ?>
<p style="color:red;"><?= $error; ?></p>
<?php endif; ?>

<input type="text" name="username" placeholder="Username" required>

<input type="password" name="password" placeholder="Password" required>

<button type="submit" name="login">
Login
</button>
</form>
STEP 6 — Dashboard Page

dashboard.php

<?php
require_once 'config.php';

requireLogin();
?>

<h1>Welcome, <?= clean($_SESSION['full_name']); ?></h1>

<p>You are logged in successfully.</p>

<a href="index.php?logout=true">Logout</a>
STEP 7 — Password Hashing

Password hashing ni muhimu ili password zisihifadhiwe plain text.

$hashedPassword = password_hash(
$password,
PASSWORD_DEFAULT
);

Kwa login:

password_verify(
$password,
$user['password']
);
STEP 8 — Session Security

Baada ya login successful tumia:

session_regenerate_id(true);

Hii inalinda dhidi ya session fixation.

STEP 9 — Protect Pages

Kwenye kila page ambayo user lazima awe logged in:

requireLogin();

Mfano:

<?php
require_once 'config.php';
requireLogin();
?>
STEP 10 — Logout System
if (isset($_GET['logout'])) {
logout();
}

Au tengeneza logout.php:

<?php
require_once 'config.php';

logout();
STEP 11 — CSRF Protection kwa Login Form

Generate token:

if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

Weka kwenye form:

<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>">

Validate token:

if (
empty($_POST['csrf_token']) ||
!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
) {
die("Invalid security token.");
}
STEP 12 — Bootstrap Login Form
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css&quot; rel="stylesheet">

<div class="container mt-5">
<div class="card mx-auto shadow" style="max-width:450px;">
<div class="card-body">
<h3 class="text-center mb-4">Login</h3>

<form method="POST">
<div class="mb-3">
<label>Username</label>
<input type="text" name="username" class="form-control" required>
</div>

<div class="mb-3">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>

<button type="submit" name="login" class="btn btn-success w-100">
Login
</button>
</form>
</div>
</div>
</div>
Common Mistakes kwenye PHP Login System
Kuhifadhi Password Plain Text

Usihifadhi password kama ilivyo.

Kutotumia Prepared Statements

Hii inaweza kusababisha SQL Injection.

Kutotumia Session Regeneration

Hii inaweza kusababisha session attacks.

Kuacha Pages Bila Protection

Kila page muhimu iwe na requireLogin().

Features za Secure PHP Login System
User Registration
Secure Login
Password Hashing
Session Protection
Logout System
Protected Pages
PDO Prepared Statements
Bootstrap Login Form
CSRF Protection
Mfumo Huu Unaweza Kutumika Wapi?
Admin Dashboard
School Management System
Farm Management System
Accounting System
POS System
Inventory System
Hospital System
Hotel Booking System
Hitimisho

PHP Login System ni msingi wa mfumo wowote unaohitaji user authentication.

Kwa kutumia:

PHP PDO
MySQL
Password Hashing
Sessions
CSRF Protection
Prepared Statements

unaweza kutengeneza secure login system inayofaa kwa project nyingi.

Kwa tutorials zaidi tembelea:

https://faulink.com

🚀 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.

Share this post

Comments

0
No comments yet. Be the first to comment.

Continue Reading

Subscribe

Get new updates

Jiunge upokee posts mpya, tutorials, na updates za mifumo moja kwa moja kwenye email yako.

Faulink Support