Secure PHP Authentication System (PDO + MySQL)
Hey everyone (:
In this project, I built a secure authentication system using PHP and MySQL with PDO.
The goal was to understand how login systems work and how to make them more secure.
Project Idea
This application allows users to:
- Register an account
- Login securely
- Access a protected dashboard
- Logout
Database (phpMyAdmin)
This is the users table in phpMyAdmin.
It contains:
- id → primary key
- name → user name
- user_email → email address
- password → hashed password
- birthdate→ birthdate
Passwords are stored using hashing for security.
Database Connection (PDO)
<?php
$host = "localhost";
$dbname = "sport_db";
$username = "root";
$password = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
Registration System
<?php
require "config/database.php";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$sql = "INSERT INTO users (name, user_email, password) VALUES (:name, :email, :password)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':name' => $name,
':email' => $email,
':password' => $password
]);
echo "Registration successful!";
}
?>
Login System
<?php
session_start();
require "config/database.php";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE user_email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute([':email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['name'] = $user['name'];
header("Location: dashboard.php");
exit;
} else {
echo "Invalid credentials!";
}
}
?>
Dashboard (Protected Page)
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
?>
<h1>Welcome <?php echo $_SESSION['name']; ?></h1>
Logout
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
Security Features
- Password hashing using bcrypt
- Secure queries with PDO prepared statements
- Session-based authentication
- Protection against SQL Injection
What I Learned
- Building a secure authentication system
- Using PDO in PHP
- Managing sessions
- Structuring a real web project
Future Improvements
- Add form validation
- Improve UI
- Add password reset
- Add user profile
Conclusion
This project helped me understand how authentication systems work in real applications and how to make them more secure.
Feedback is welcome!




Top comments (0)