SIMPLE LOGIN AND REGISTRATION SYSTEM IN HTML CSS AND JAVA SCRIPT

Introduction to the Project

This project is a Secure User Authentication System built with a clear separation of client-side and server-side technologies. It serves as a foundational template for any web application that requires user accounts.

The system distinguishes between two types of users: Admins and Clients (regular users) . Upon login, users are redirected to a respective dashboard that displays features and content specific to their role. The system includes secure password hashing, session management, and basic validation to ensure a robust starting point for larger projects like e-commerce sites, forums, or membership portals.


Features of the Project

Core Features

  • User Registration: New users can create an account by providing a username, email, and password.
  • User Login: Registered users can log in with their credentials.
  • Password Hashing: Passwords are securely hashed using PHP's password_hash() before being stored in the database.
  • Session Management: PHP sessions are used to keep users logged in and to restrict access to certain pages.
  • Role-Based Redirection: Users are redirected to different dashboards based on their role (Admin or Client).

Admin Side Features

  • Admin Dashboard: A dedicated page for administrators.
  • View All Users: Admins can view a list of all registered users and their roles.
  • Elevated Privileges: A simple example of how an admin can access data regular users cannot.

Client Side Features

  • Client Dashboard: A dedicated page for regular logged-in users.
  • Personalized Welcome: Displays a welcome message with the user's username.
  • Profile Overview: Shows basic account information to the user.

Technology Stack

  • Frontend: HTML5, CSS3, JavaScript (for basic form validation and interactivity)
  • Backend: PHP (Core PHP, no frameworks)
  • Database: MySQL
  • Server: Apache (XAMPP / WAMP / MAMP recommended for local development)

Project File Structure

Here is the recommended file structure for the project. Create these folders and files in your web server's root directory (e.g., htdocs for XAMPP).

login-system/
│
├── assets/
│   ├── css/
│   │   └── style.css
│   └── js/
│       └── script.js
│
├── includes/
│   ├── config.php
│   ├── register.php
│   └── login.php
│
├── admin/
│   ├── dashboard.php
│   └── view_users.php
│
├── client/
│   └── dashboard.php
│
├── index.php
├── register.php
├── login.php
├── logout.php
└── sql/
└── database.sql

Database Setup

1. Create the Database and Table

Open phpMyAdmin (usually at http://localhost/phpmyadmin) and run the SQL script below. This script is also provided in the sql/database.sql file.

File: sql/database.sql

CREATE DATABASE IF NOT EXISTS `login_system_db`;
USE `login_system_db`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL UNIQUE,
`email` varchar(100) NOT NULL UNIQUE,
`password` varchar(255) NOT NULL,
`role` enum('admin','client') DEFAULT 'client',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Insert a default admin user (password: admin123)
INSERT INTO `users` (`username`, `email`, `password`, `role`) VALUES
('admin', '[email protected]', '$2y$10$YourHashedPasswordHere', 'admin');

Note: You will need to generate a real hash for the default admin password. You can do this by registering a user as 'admin' first, then copying the hash from the database, or by using an online tool to hash the string admin123 and pasting it here.


Code Implementation

Step 1: Database Configuration

File: includes/config.php
This file contains the database connection details. It will be included in all pages that need to interact with the database.

<?php
session_start(); // Start the session on every page
$host = 'localhost'; // or your host
$dbname = 'login_system_db';
$username = 'root'; // your MySQL username
$password = ''; // your MySQL password
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>

Step 2: Registration Logic

File: includes/register.php
This file handles the server-side logic for user registration.

<?php
require_once 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$role = 'client'; // Default role for new registrations
$errors = [];
// Basic validation
if (empty($username) || empty($email) || empty($password)) {
$errors[] = "All fields are required.";
}
if ($password !== $confirm_password) {
$errors[] = "Passwords do not match.";
}
if (strlen($password) < 6) {
$errors[] = "Password must be at least 6 characters.";
}
// Check if username or email already exists
if (empty($errors)) {
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt->execute([$username, $email]);
if ($stmt->fetch()) {
$errors[] = "Username or Email already exists.";
}
}
// If no errors, insert user into database
if (empty($errors)) {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
if ($stmt->execute([$username, $email, $hashed_password, $role])) {
$_SESSION['success_message'] = "Registration successful! You can now log in.";
header("Location: ../login.php");
exit();
} else {
$errors[] = "Something went wrong. Please try again.";
}
}
// If there were errors, store them in session to display on the form page
if (!empty($errors)) {
$_SESSION['errors'] = $errors;
$_SESSION['form_data'] = $_POST; // To repopulate the form
header("Location: ../register.php");
exit();
}
} else {
// If someone tries to access this file directly without POST
header("Location: ../register.php");
exit();
}
?>

Step 3: Login Logic

File: includes/login.php
This file handles the server-side logic for user login.

<?php
require_once 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username_email = trim($_POST['username_email']);
$password = $_POST['password'];
$errors = [];
if (empty($username_email) || empty($password)) {
$errors[] = "Both fields are required.";
}
if (empty($errors)) {
// Fetch user by username or email
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ?");
$stmt->execute([$username_email, $username_email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
// Password is correct, start a session
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['user_role'] = $user['role'];
// Redirect based on role
if ($user['role'] == 'admin') {
header("Location: ../admin/dashboard.php");
} else {
header("Location: ../client/dashboard.php");
}
exit();
} else {
$errors[] = "Invalid username/email or password.";
}
}
// If there were errors
if (!empty($errors)) {
$_SESSION['errors'] = $errors;
header("Location: ../login.php");
exit();
}
} else {
header("Location: ../login.php");
exit();
}
?>

Step 4: Frontend Pages (HTML, CSS, JS)

File: index.php
A simple landing page.

<?php include 'includes/config.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home - Login System</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<h1>Welcome to the Authentication System</h1>
<p>This is a simple demonstration of a login and registration system with role-based access.</p>
<?php if (isset($_SESSION['user_id'])): ?>
<p>You are logged in as <strong><?php echo htmlspecialchars($_SESSION['username']); ?></strong>.</p>
<a href="<?php echo ($_SESSION['user_role'] == 'admin') ? 'admin/dashboard.php' : 'client/dashboard.php'; ?>">Go to Dashboard</a>
<a href="logout.php">Logout</a>
<?php else: ?>
<a href="login.php" class="btn">Login</a>
<a href="register.php" class="btn">Register</a>
<?php endif; ?>
</div>
</body>
</html>

File: register.php
The registration form.

<?php include 'includes/config.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<h2>Register</h2>
<?php
if (isset($_SESSION['errors'])) {
echo '<div class="error">';
foreach ($_SESSION['errors'] as $error) {
echo '<p>' . htmlspecialchars($error) . '</p>';
}
echo '</div>';
unset($_SESSION['errors']);
}
$form_data = $_SESSION['form_data'] ?? [];
unset($_SESSION['form_data']);
?>
<form action="includes/register.php" method="POST" onsubmit="return validateRegisterForm()">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php echo htmlspecialchars($form_data['username'] ?? ''); ?>" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<?php echo htmlspecialchars($form_data['email'] ?? ''); ?>" required>
</div>
<div class="form-group">
<label for="password">Password (min. 6 characters):</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password:</label>
<input type="password" id="confirm_password" name="confirm_password" required>
</div>
<button type="submit" class="btn">Register</button>
</form>
<p>Already have an account? <a href="login.php">Login here</a>.</p>
</div>
<script src="assets/js/script.js"></script>
</body>
</html>

File: login.php
The login form.

<?php include 'includes/config.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<h2>Login</h2>
<?php
if (isset($_SESSION['success_message'])) {
echo '<div class="success"><p>' . htmlspecialchars($_SESSION['success_message']) . '</p></div>';
unset($_SESSION['success_message']);
}
if (isset($_SESSION['errors'])) {
echo '<div class="error">';
foreach ($_SESSION['errors'] as $error) {
echo '<p>' . htmlspecialchars($error) . '</p>';
}
echo '</div>';
unset($_SESSION['errors']);
}
?>
<form action="includes/login.php" method="POST" onsubmit="return validateLoginForm()">
<div class="form-group">
<label for="username_email">Username or Email:</label>
<input type="text" id="username_email" name="username_email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn">Login</button>
</form>
<p>Don't have an account? <a href="register.php">Register here</a>.</p>
</div>
<script src="assets/js/script.js"></script>
</body>
</html>

File: logout.php
Destroys the session and logs the user out.

<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
exit();
?>

Step 5: Client and Admin Dashboards

File: client/dashboard.php

<?php
require_once '../includes/config.php';
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
header("Location: ../login.php");
exit();
}
// Optional: Ensure only clients access this page (though role check is good practice)
if ($_SESSION['user_role'] != 'client') {
header("Location: ../admin/dashboard.php"); // Redirect admin to their dashboard
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client Dashboard</title>
<link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<div class="container">
<h2>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</h2>
<p>This is your Client Dashboard. You have successfully logged in.</p>
<p><strong>Your Role:</strong> <?php echo htmlspecialchars($_SESSION['user_role']); ?></p>
<p><a href="../logout.php">Logout</a></p>
<p><a href="../index.php">Back to Home</a></p>
</div>
</body>
</html>

File: admin/dashboard.php

<?php
require_once '../includes/config.php';
// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
header("Location: ../login.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard</title>
<link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<div class="container">
<h2>Admin Dashboard</h2>
<p>Welcome, <strong><?php echo htmlspecialchars($_SESSION['username']); ?></strong>! You have admin privileges.</p>
<ul>
<li><a href="view_users.php">View All Users</a></li>
<li><a href="../logout.php">Logout</a></li>
</ul>
</div>
</body>
</html>

File: admin/view_users.php
An admin-only page to see all registered users.

<?php
require_once '../includes/config.php';
// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
header("Location: ../login.php");
exit();
}
// Fetch all users from the database
$stmt = $pdo->query("SELECT id, username, email, role, created_at FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Users - Admin</title>
<link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<div class="container">
<h2>All Registered Users</h2>
<table border="1" cellpadding="10" cellspacing="0" style="width:100%; border-collapse: collapse;">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Registered On</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo htmlspecialchars($user['id']); ?></td>
<td><?php echo htmlspecialchars($user['username']); ?></td>
<td><?php echo htmlspecialchars($user['email']); ?></td>
<td><?php echo htmlspecialchars($user['role']); ?></td>
<td><?php echo htmlspecialchars($user['created_at']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p><a href="dashboard.php">Back to Dashboard</a></p>
</div>
</body>
</html>

Step 6: Assets (CSS & JS)

File: assets/css/style.css
Basic styling for the project.

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 100%;
max-width: 600px;
}
h1, h2 {
text-align: center;
margin-bottom: 20px;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: 600;
color: #555;
}
input[type="text"],
input[type="email"],
input[type="password"] {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
.btn {
display: inline-block;
background: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
text-decoration: none;
font-size: 16px;
width: 100%;
}
.btn:hover {
background: #0056b3;
}
.error {
background: #f8d7da;
color: #721c24;
padding: 10px;
border-radius: 4px;
margin-bottom: 20px;
border: 1px solid #f5c6cb;
}
.success {
background: #d4edda;
color: #155724;
padding: 10px;
border-radius: 4px;
margin-bottom: 20px;
border: 1px solid #c3e6cb;
}
p {
margin-top: 15px;
text-align: center;
}
a {
color: #007bff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}

File: assets/js/script.js
JavaScript for client-side validation.

function validateRegisterForm() {
let password = document.getElementById('password').value;
let confirm = document.getElementById('confirm_password').value;
if (password.length < 6) {
alert('Password must be at least 6 characters long.');
return false;
}
if (password !== confirm) {
alert('Passwords do not match.');
return false;
}
return true;
}
function validateLoginForm() {
let username = document.getElementById('username_email').value;
let password = document.getElementById('password').value;
if (username.trim() === '' || password.trim() === '') {
alert('Both fields are required.');
return false;
}
return true;
}

How to Use the Project (Step-by-Step Guide)

Prerequisites

  • Install a local server environment like XAMPP, WAMP, or MAMP.
  • A code editor (like VS Code).
  • A web browser.

Setup Instructions

  1. Start your local server: Open XAMPP Control Panel and start Apache and MySQL.
  2. Create Project Folder:
    • Navigate to the htdocs folder (if using XAMPP, usually C:\xampp\htdocs\).
    • Create a new folder named login-system.
  3. Create File Structure: Inside the login-system folder, create all the subfolders and files exactly as shown in the Project File Structure section above.
  4. Copy the Code: Copy and paste the corresponding code provided in this document into each file you created.
  5. Set up the Database:
    • Open your browser and go to http://localhost/phpmyadmin.
    • Click on the "SQL" tab.
    • Copy the entire SQL script from the sql/database.sql section and paste it into the text area.
    • Click "Go" to execute the script. This will create the database login_system_db and the users table.
    • Important: Remember to update the default admin password hash as mentioned in the database setup notes. For a quick start, you can register a new user with the username 'admin' and then manually change its role to 'admin' in phpMyAdmin.
  6. Configure Database Connection:
    • Open the file includes/config.php.
    • Ensure the $username and $password variables match your MySQL credentials (default for XAMPP is root and empty password '').
  7. Run the Project:
    • Open your web browser and go to: http://localhost/login-system/
    • You should see the homepage.
  8. Test the Functionality:
    • Register a new client: Click on "Register" and create a new user. You will be redirected to the login page with a success message.
    • Login as a client: Use the credentials you just registered with. You should be taken to the Client Dashboard.
    • Logout: Click the logout link.
    • Login as Admin: Use the default admin credentials ([email protected] / admin123) if you set them up, or use the admin account you created manually. You will be taken to the Admin Dashboard.
    • Test Admin Feature: From the admin dashboard, click "View All Users" to see the list of registered users.

Conclusion

You have now successfully built a complete, secure, and role-based Login and Registration System. This project provides a solid foundation that you can easily integrate into future web development projects. The clear separation of code and files makes it easy to understand, maintain, and expand upon.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper