This project aims to build a secure and user-friendly member login system using PHP and MySQL, allowing administrators to manually add users and create exclusive content for registered members. The system will feature a login page where users authenticate with their credentials, an admin panel for managing users and pages, and a members-only area where restricted content is displayed. By implementing role-based access control, session management, and secure password handling, the project ensures that only authorized users can access protected content, making it ideal for communities, subscription-based services, or internal company portals.
We’ll walk through creating each step for a simple member login system using PHP and MySQL. In our example, administrators can manually add new users and create pages that are accessible only to logged‐in members. We’ll cover how to design the database, build the login process, create an admin panel for managing users and content, and finally display member-only pages. Let’s get started!
1. Overview
The project has two main parts:
- Member Login & Session Management: Users log in with their credentials. Upon successful authentication, a session is started and they can access protected content.
- Admin Panel: Administrators can add new users (with roles such as “admin” or “member”) and create pages that are visible only to members.
By using prepared statements and secure password handling, we’ll also keep our application safe from common security vulnerabilities.
2. Database Setup
First, create a MySQL database (for example, named membership_db) and two tables: one for users and one for content pages.
SQL for the users table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role ENUM('admin','member') NOT NULL DEFAULT 'member'
);
SQL for the pages table:
CREATE TABLE pages (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
is_member_only BOOLEAN NOT NULL DEFAULT 1
);
This schema lets us store user details (with secure hashed passwords) and pages with a flag to indicate if the content is for members only.
3. Setting Up the Project
Create the following PHP files for your project:
- db.php: Contains the database connection code.
- login.php: The login form and processing logic.
- admin.php: The admin panel for adding users and pages.
- members.php: A members-only area that displays the protected pages.
- logout.php: A simple logout script.
4. Database Connection (db.php)
We’ll use PDO for a secure and flexible database connection:
<?php
// db.php
$host = 'localhost';
$db = 'membership_db'; // change to your database name
$user = 'your_db_user'; // change to your database user
$pass = 'your_db_pass'; // change to your database password
$dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
exit("Database connection failed: " . $e->getMessage());
}
?>
5. Creating the Login Page (login.php)
This page presents a login form and processes the submitted credentials. On success, a session is started and the user is redirected to the member area.
<?php
// login.php
session_start();
require 'db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
// Retrieve user from the database
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
// Verify user exists and password is correct
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
header("Location: members.php");
exit;
} else {
$error = "Invalid username or password!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Member Login</title>
</head>
<body>
<h1>Login</h1>
<?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
<form method="post" action="">
<label>Username: <input type="text" name="username" required></label><br><br>
<label>Password: <input type="password" name="password" required></label><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Tip: Always use
password_hash()when storing passwords (as shown later) andpassword_verify()during login.
6. Building the Admin Panel (admin.php)
Only logged-in administrators should access this panel. The admin panel lets you:
- Add new users: Manually create a new user with a username, email, password (which is hashed), and role.
- Add new pages: Create pages with a title and content. A checkbox determines if the page is for members only.
<?php
// admin.php
session_start();
require 'db.php';
// Check if the user is logged in and is an admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
header("Location: login.php");
exit;
}
// Process adding a new user
if (isset($_POST['add_user'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$role = $_POST['role'];
$stmt = $pdo->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)");
$stmt->execute([$username, $email, $password, $role]);
$user_message = "User added successfully!";
}
// Process adding a new page
if (isset($_POST['add_page'])) {
$title = $_POST['title'];
$content = $_POST['content'];
// Checkbox returns 'on' if checked; if unchecked, it won’t be set.
$is_member_only = isset($_POST['is_member_only']) ? 1 : 0;
$stmt = $pdo->prepare("INSERT INTO pages (title, content, is_member_only) VALUES (?, ?, ?)");
$stmt->execute([$title, $content, $is_member_only]);
$page_message = "Page added successfully!";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin Panel</title>
</head>
<body>
<h1>Admin Panel</h1>
<p>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</p>
<h2>Add New User</h2>
<?php if (isset($user_message)) echo "<p style='color:green;'>$user_message</p>"; ?>
<form method="post">
<label>Username: <input type="text" name="username" required></label><br><br>
<label>Email: <input type="email" name="email" required></label><br><br>
<label>Password: <input type="password" name="password" required></label><br><br>
<label>Role:
<select name="role">
<option value="member">Member</option>
<option value="admin">Admin</option>
</select>
</label><br><br>
<button type="submit" name="add_user">Add User</button>
</form>
<h2>Add New Page</h2>
<?php if (isset($page_message)) echo "<p style='color:green;'>$page_message</p>"; ?>
<form method="post">
<label>Title: <input type="text" name="title" required></label><br><br>
<label>Content:<br>
<textarea name="content" rows="5" cols="40" required></textarea>
</label><br><br>
<label>Member Only? <input type="checkbox" name="is_member_only" checked></label><br><br>
<button type="submit" name="add_page">Add Page</button>
</form>
<p><a href="members.php">Go to Members Area</a></p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
Security Note: Since this is an admin panel, you must ensure that only administrators can access this file. Always check the user’s role using sessions.
7. Creating the Members-Only Area (members.php)
This page is accessible only if a user is logged in. It fetches and displays pages marked as member-only from the database.
<?php
// members.php
session_start();
require 'db.php';
// Redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
// Retrieve member-only pages
$stmt = $pdo->prepare("SELECT * FROM pages WHERE is_member_only = 1");
$stmt->execute();
$pages = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<title>Members Area</title>
</head>
<body>
<h1>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</h1>
<p>This is the members-only area.</p>
<h2>Available Pages</h2>
<ul>
<?php foreach ($pages as $page): ?>
<li>
<h3><?php echo htmlspecialchars($page['title']); ?></h3>
<p><?php echo nl2br(htmlspecialchars($page['content'])); ?></p>
</li>
<?php endforeach; ?>
</ul>
<?php if ($_SESSION['role'] == 'admin'): ?>
<p><a href="admin.php">Go to Admin Panel</a></p>
<?php endif; ?>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
8. Logging Out (logout.php)
A simple logout script destroys the session and redirects the user back to the login page.
<?php
// logout.php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
9. Security Best Practices
- Password Storage: Always hash passwords using functions like
password_hash()and verify usingpassword_verify(). - SQL Injection Prevention: Use prepared statements (as shown) to avoid SQL injection.
- Session Security: Regenerate session IDs on login and ensure session data is properly managed.
- Input Sanitization: Use
htmlspecialchars()when outputting user data to prevent Cross-Site Scripting (XSS).
10. The basic concept
You now have a basic member login system using PHP and MySQL. The system includes:
- A login page where users authenticate.
- An admin panel that allows administrators to add new users and member-only pages.
- A members-only area that displays restricted content.
This example is a starting point. In a production environment, you would likely add more robust error handling, form validation, and security measures. With this foundation, you can further extend the system by adding features like password recovery, user profile management, and more advanced content management. Happy coding!