Welcome to a tutorial on how to create a membership system with PHP and MySQL. Planning to open a “members only” section on your website? There are a couple of things that we need to cover – Database, registration, login, and more. Read on for the step-by-step guide!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PHP MYSQL MEMBERSHIP SYSTEM
All right, let us now get into the steps of constructing a membership system with PHP and MySQL.
TUTORIAL VIDEO
STEP 1) MEMBERS DATABASE
CREATE TABLE `members` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`start` datetime NOT NULL DEFAULT current_timestamp(),
`till` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `members`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`),
ADD KEY `name` (`name`);
ALTER TABLE `members`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
First, we start by creating a table to store all the members:
id
Member ID, primary key.name
Member’s name.email
Member’s email, unique to prevent duplicates.password
Login password.start
Member since.till
Membership expiry date, optional.
Feel free to add more fields as required – Maybe a “member level” if you offer different tiers.
STEP 2) PHP MEMBERSHIP LIBRARY
<?php
class Member {
// (A) CONSTRUCTOR - CONNECT TO THE DATABASE
private $pdo = null;
private $stmt = null;
public $error;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET MEMBER BY ID OR EMAIL
function get ($id) {
$this->query(sprintf("SELECT * FROM `members` WHERE `%s`=?",
is_numeric($id) ? "id" : "email"
), [$id]);
return $this->stmt->fetch();
}
// (E) ADD MEMBER
function add ($name, $email, $password, $till=null) {
// (E1) CHECK IF EMAIL ALREADY REGISTERED
if ($this->get($email)) {
$this->error = "$email is already registered";
return false;
}
// (E2) SAVE MEMBER DATA
$this->query(
"INSERT INTO `members` (`name`, `email`, `password`, `till`) VALUES (?,?,?,?)",
[$name, $email, password_hash($password, PASSWORD_DEFAULT), $till]
);
return true;
}
// (F) VERIFICATION
function verify ($email, $password) {
// (F1) GET MEMBER
$member = $this->get($email);
$pass = is_array($member);
// (F2) CHECK MEMBERSHIP EXPIRY
if ($pass && $member["till"]!="") {
if (strtotime("now") >= strtotime($member["till"])) {
$pass = false;
}
}
// (F3) CHECK PASSWORD
if ($pass) { $pass = password_verify($password, $member["password"]); }
// (F4) REGISTER MEMBER INTO SESSION
if ($pass) {
foreach ($member as $k=>$v) { $_SESSION["member"][$k] = $v; }
unset($_SESSION["member"]["password"]);
}
// (F5) RESULT
if (!$pass) { $this->error = "Invalid email/password"; }
return $pass;
}
}
// (G) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (H) START
session_start();
$_MEM = new Member();
This library looks difficult at first, but keep calm and study carefully:
- (A, B, H) When
$_MEM = new Member()
is created, the constructor automatically connects to the database. The destructor closes the connection. - (C)
query()
A helper function to run an SQL statement. - (E & F) The actual membership functions.
add()
Add a new member.verify()
Verify the user credentials, register user information into$_SESSION["member"]
.
- (G) Database settings – Change to your own.
- (H) Start the session and “engine”.
STEP 3) MEMBER REGISTRATION PAGE
<?php
// (A) LOAD LIBRARY + REDIRECT IF SIGNED IN
require "2-lib-member.php";
if (isset($_SESSION["member"])) {
header("Location: 5-protected.php");
exit();
}
// (B) PROCESS FORM SUBMISSION
// redirect to a "nice welcome page" in your own project
// this demo will redirect to login page directly
if (count($_POST)!=0) {
if ($_MEM->add($_POST["name"], $_POST["email"], $_POST["password"])) {
header("Location: 4-login.php");
exit();
}
} ?>
<!-- (C) REGISTRATION FORM -->
<?php
if ($_MEM->error!="") { echo "<div class='error'>".$_MEM->error."</div>"; }
?>
<form method="post">
<h1>REGISTRATION</h1>
<label>Name</label>
<input type="text" name="name" required>
<label>Email</label>
<input type="email" name="email" required>
<label>Password</label>
<input type="password" name="password" required>
<input type="submit" value="Register">
</form>
Now that the database and system settings are in place, let us build the registration page. It is easier to study this page from the bottom up:
- (C) HTML registration form.
- (B) When the form is submitted, we will use the library to process the registration.
- If successful, we redirect the user to the login page.
- If it fails, we show the error message.
- (A) Members who are already signed in will be redirected to the “members only” page.
STEP 4) MEMBER LOGIN PAGE
<?php
// (A) LOAD LIBRARY
require "2-lib-member.php";
// (B) CHECK LOGIN CREDENTIALS
if (count($_POST)!=0) {
$_MEM->verify($_POST["email"], $_POST["password"]);
}
// (C) REDIRECT IF SIGNED IN
if (isset($_SESSION["member"])) {
header("Location: 5-protected.php");
exit();
} ?>
<!-- (D) LOGIN FORM -->
<?php
if ($_MEM->error!="") { echo "<div class='error'>".$_MEM->error."</div>"; }
?>
<form method="post">
<h1>LOGIN</h1>
<label>Email</label>
<input type="email" name="email" required>
<label>Password</label>
<input type="password" name="password" required>
<input type="submit" value="Login">
</form>
With the registration complete, the next obvious step is to deal with the login. Again, it is easier to start from the bottom:
- (D) A good old login form.
- (A & B) When the login form is submitted, we load the library and do a verification check.
- (C) On a valid sign-in, we redirect the user to the “members only” section; Users who are already signed in will be redirected, and they won’t get to see the login page.
STEP 5) PROTECTED MEMBER PAGES & LOGOUT
<?php
// (A) LOAD LIBRARY
require "2-lib-member.php";
// (B) SIGN OUT
if (isset($_POST["out"])) {
unset($_SESSION["member"]);
}
// (C) NOT SIGNED IN - BACK TO LOGIN PAGE
if (!isset($_SESSION["member"])) {
header("Location: 4-login.php");
exit();
} ?>
<form method="post">
<h1>MEMBER PAGE</h1>
<p>You are in!</p>
<input type="hidden" name="out" value="1">
<input type="submit" value="Sign Out">
</form>
- (A & C) In all your “members-only” pages, simply redirect users back to the login page if they are not signed in.
- (B) To logout, simply
unset($_SESSION["member"])
.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
IMPROVEMENT IDEAS
This is only a simple barebones membership system, a lot can be done to make it better:
- Add
role
column to themembers
table. Differentiate between admin and members, maybe even add different membership levels. - Add an admin panel to manage the members and content.
- Complete your own “nice registration process” – Send an email, redirect to a welcome page, etc…
- For paid memberships, integrate with your payment processor – Paypal, Stripe, Apple Pay, Google Pay, etc…
- Secure your “members only” content. An easy way is to put the contents outside of the public HTTP folder and use PHP to read them.
- Complete your own PHP library – Add an “edit member” function, get expiring memberships, reports, etc…
The possibilities are endless, and I cannot offer free consultations to everyone. The rest is up to you to complete.
LINKS & REFERENCES
- PHP Forgotten Password Recovery – Code Boxx
- Registration With Email Confirmation – Code Boxx
- User Role Management – Code Boxx
- Simple Admin Panel – Code Boxx
- PHP Email With Template – Code Boxx
- Simple Comment System – Code Boxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Does the registrant get a welcome email after they register?
No, but you can make that change with a just few lines in
2-lib-member.php, function add()
.https://code-boxx.com/send-email-php/
This is a great tutorial! Thank you for putting it together and sharing.
It is ok ,But how can I integrate my payment gateways in this codes during sign-up.For example I would like to use PayPal and Flutter wave as payment gateway.
As above – IMPROVEMENT IDEAS. Modify
3-register.php
and study the payment gateway API on your own. Good luck.https://code-boxx.com/faq/#help “Help and requests on a deeper level.”