Want to have your users create accounts so they can save and share content with each other? Well there is no other easier and must have code on your site besides a member system. Allow your users to register and login to your site then access your exclusive users only area. Here is how to do it all!
Let’s plan out our Member System
In order to figure out what all we want out of our member system we need to think it all out. I’m going to start with a simple setup that only takes a few fields of data from the user. Let say a username, email address and password to keep it simple. We will even force to users to have a strong password and make it so we can send an account activation email. I’m going to add time tracker that will update every time the user logs in as well. And and last but not least a date tracker to remember when the account was created.
What our member system can do:
- register a new account
- login to user account
- track the last login time of users
- have a member only area
- logout page (obviously!)
Setup the database using phpMyAdmin
Now that we have it all planned out, we can create our database to store all the users’ data in. Lets call it users (I know, I’m really racking my brain on this one).

For this particular instance, we only need 7 fields in our database. Let’s talk about each:
- id – this is going to be a unique identifier for each user. We need to make sure the id is an integer and set to auto increment and primary key. This is a must!!! When you get into more complex stuff, using the user’s account id makes it super simple to link database records together.
- username – this should be self explanatory. I set mine to a 50 character varchar. Very rarely will user’s have a username longer than 10-15 characters, so 50 should take care of it.
- email – the user’s email address, a 100 character varchar.
- password – we will use some basic encryption for our users’ passwords. So a varchar of 50 characters will do nicely. Later on, you’ll see us use the md5() function to create a basic password hash for some simple security.
- date_created – this will store a time() value of when the user created their account.
- last_login – we can track the last time the user logged in by updating this record here. Again will be from the time() function.
- status – track the account activation status. We can check this value to see if the user has activated their account or not, and based on that let them login or give them a notice to activate their account.
Connect to MySQL database using PHP
Now that we have out database created, we are going to create a simple connect script. By putting our code to connect to our database in a single file, say connect.php, we can then include() that file and have one centralized location to update our server and database connection information. Doing this is really required, but it is certainly a good practice. I for sure recommend doing it!
<?php
$conn = mysqli_connect("localhost", "root", "password", "code_projects");
?>
Just save that as connect.php and we will get to it later!
How to Make a User Registration Page for Member System
The first part of any website’s member system is the ability for users to register! Pretty quick and easy to write from scratch, this simple form and script will let any user register with only a username and password.
Our register page is going to come in a few parts that can be divided into the front-end display, which is the html page that will be displayed to the user, and the back-end script. Below is a basic outline and order of how our it is going to be coded.
<?php
// connect to the database
// check for a user being logged in
// process the register form data
?>
<html>
display a header
display the error message (if there is one)
display the register form
</html>
We are going to start with the front-end display to get us a working form. This way we will know exactly how to code our back-end script to process the data.
Register Page Front End
The header for this tutorial will just be a simple one with a few links just for some super basic navigation.
<h1>member system tutorial - register</h1>
<a href="./index.php">Home</a> |
<a href="./register.php">Register</a> |
<a href="./login.php">Login</a>
<hr />
Below our header is where I am going to display the form’s error message. This message will give the user an idea of what they did wrong and need to correct before they can create their account. Basically what I am going to do is create a variable named $success and $error_msg. We will do a simple check for these two variables being set, and based on if they are set or created, we display a different type of message. The idea is that if there is an error while processing the data, we can set the error message in the $error_msg variable, and then it will get displayed to the user and we will strop processing the info. If the user successfully creates their account, we will set $success to true and display a success message in green (because green is always good, am I right??).
<?php
// check to see if the user successfully created an account
if (isset($success) && $success = true){
echo '<font color="green">Yay!! Your account has been created. <a href="./login.php">Click here</a> to login!<font>';
}
// check to see if the error message is set, if so display it
else if (isset($error_msg))
echo '<font color="red">'.$error_msg.'</font>';
else
echo ''; // do nothing
?>
Now we can create the form that the user is going to see and interact with. If you think back to our database setup, we have only 3 fields that the user has the ability to enter: the username, password, and email address. Out of good practice, I am going to add an additional password field for the user to confirm their password. Also, some text to display to the user to let them know what fields are required and the password strength required. And of course a button so submit the data.
I am also going to require the user to use a somewhat strong password. Let’s say 5 characters long and at least one special character of one of these: !#$.,:;(). This wont give the use the most secure password, but it will give you an idea of how to force stronger passwords to your users.
<form action="./register.php" method="POST" name="registerForm">
<table cellpadding="4px">
<tr>
<td>Username: <font color="red">*</font></td>
</tr>
<tr>
<td><input type="text" value="" name="username" size="35" /></td>
</tr>
<tr>
<td>Email Address:</td>
</tr>
<tr>
<td><input type="text" value="" name="email" size="35" /></td>
</tr>
<tr>
<td>Password: <font color="red">*</font></td>
</tr>
<tr>
<td><input type="password" value="" name="passwd" size="35" /></td>
</tr>
<tr>
<td>password must be at least 5 characters and<br /> have a special character, e.g. !#$.,:;()</font></td>
</tr>
<tr>
<td>Confirm Password: <font color="red">*</font></td>
</tr>
<tr>
<td><input type="password" value="" name="passwd_again" size="35" /></td>
</tr>
<tr>
<td>
<input type="submit" name="registerBtn" value="Register" />
<font color="red">*</font> = required fields
</td>
</tr>
</table>
</form>
If you notice, I am putting our register form in a simple table just to align everything nicely for the user. The important thing to note here is the form action, the names of the text boxes, and the name of the submit button. All of these are going to be crucial in the back-end script to retrieve the data after the user submits the form. Also note the form method, POST, which will hide the form data from the user instead of sending it to the url like GET will.
Register Page Back-End Script
Like I went over earlier, we put our database connection code into the super obviously named script connect.php. We can now use the require_once() function to use the code in that script. You can think of it like an automatic copy and paste from a file. It just takes all code in the file we are requiring, and makes it all available in the current file we are coding in like it was all there.
<?php
// include our connect script
require_once("connect.php");
// check to see if there is a user already logged in, if so redirect them
session_start();
if (isset($_SESSION['username']) && isset($_SESSION['userid']))
header("Location: ./index.php"); // redirect the user to the home page
?>
The session code is the magic of our member system. Using session, we can actually allow users to login to our site. Above we create a session and check to see if a user is currently signed in to our site. If they are signed in, then we redirect them to the home page. Why you may ask? Because why would they need to be on the register page if they already have an account?? Duhh! I’ll explain this code later because it will make more sense there. Trust me.
Where all the good important code is at (for the register page)
Here is a quick run down of what we are about to code: make sure the user supplied all the required form data, then make sure the password and the confirm password match, then make sure the password is strong enough. After we verify the data is all valid, we can start checking the database to see if the username is already taken. After that, we can create the new database record for the user who is registering. Let’s get to it!
We need too see if the user actual clicked the register button. If they didn’t, we don’t really need to do anything other than display the normal register form to them. If they did, then we need to get and start processing all the data. Since we are using a POST form, we need to get the POST data using our php code. All the POSTed data from the form will be in the $_POST array variable. You can use the name of the form element as the array key and get the specific data you are looking for, like I did below.
if (isset($_POST['registerBtn'])){
// get all of the form data
$username = $_POST['username'];
$email = $_POST['email'];
$passwd = $_POST['passwd'];
$passwd_again = $_POST['passwd_again'];
// next code block
}
Now we need to make sure the user supplied all the required form data. For this instance, I didn’t require the user to enter an email. So we just have username, password, and confirm password as the required fields. So if we make sure that each variable is not an empty string, then that means there is some text in there, right? We can then check to see if the password and confirm password are exactly the same text, caps and all. By using three equal signs (that’s ===) in our if statement, the strings we are comparing are check to match case too. So if we compare “hello” to “HeLLo” using two equal signs then you get a true result because our code says “yes hello and hello are the same word”. But if we compare them using three equal signs, our code is like “NO! Stop right there. Those words do not match. Big ol’ false!” Make sense?
After we have checked to see if the user typed their password exactly as they meant to, we can make sure it is strong enough to meet our ohhh so impressive criteria for a secure password. Using strlen() we make sure it is long enough to meet our 5 character minimum. Then using the strpbrk() function we can check to see if any our special characters list is present at all. The function will return false if none of them are present, and will return a string if any are present. You can read more on the function on the php.net reference. This is just a super quick and easy way to check for a list of special characters just existing in the string, because other than existing we don’t really care about them.
// verify all the required form data was entered
if ($username != "" && $passwd != "" && $passwd_again != ""){
// make sure the two passwords match
if ($passwd === $passwd_again){
// make sure the password meets the min strength requirements
if ( strlen($passwd) >= 5 && strpbrk($passwd, "!#$.,:;()") != false ){
// next code block
}
else
$error_msg = 'Your password is not strong enough. Please use another.';
}
else
$error_msg = 'Your passwords did not match.';
}
else
$error_msg = 'Please fill out all required fields.';
Now that we know all of our form data is good and ready for use, we can start doing some database checks. First we check to see if the username is already in the database. If there are zero records returned, then the username is not in the database. If anything else is returned, then the username is taken. Next we need to create some extra variables to store some of the other random data we need to store in the database record for the user account we are about to create. Below this code block is an explanation of each of the variables.
DISCLAIMER: I do want to point out that for the purpose of this tutorial we are not using a very complex password encryption. I am simply doing it for the effect of not storing the password in plain-text (don’t ever do that, it’s just bad). If you want to learn how to do something more substantial and secure, check out our password security tutorial. I go into detail on different methods to creating and storing more secure passwords using php.
// query the database to see if the username is taken
$query = mysqli_query($conn, "SELECT * FROM users WHERE username='{$username}'");
if (mysqli_num_rows($query) == 0){
// create and format some variables for the database
$id = '';
$passwd = md5($passwd);
$date_created = time();
$last_login = 0;
$status = 1;
// next code block
}
else
$error_msg = 'The username <i>'.$username.'</i> is already taken. Please use another.';
- $id – we need a place holder for the auto incrementing id that the database will assign.
- $passwd – we are adding some basic encryption to to the user’s password using the md5() hash
- $date_created – using the time() function we can get a time stamp at the exact moment that the user creates their account. We can use this later to display using date()
- $last_login – later on we will use this to track when the user logs in. We shall set it to zero because they have not logged in yet.
- $status – using this field, we can track the accounts status, such as activating via email or disabling it for admin purposes, or really what ever floats your boat. I am going to set to 1 (one) by default, meaning an active account and may login immediately.
Now we can finally create the database record for the user’s account. Using an INSERT query, we can very carefully list out all of our database record information.
If you need help with understanding the basics of how queries work. Or even general database operations, check my other tutorial on MySQLi database operations.
After we INSERT the record, as a good practice, I am going to make sure the record was actually added (because you never know, there could have been some sort of error.) Since before we made sure the username did NOT exist, now if we check to see if it DOES exist and we find a record with it assigned we know our new account was created in the database. Lastly we just set our $success variable to true because the user completed their registration and their account was created.
// insert the user into the database
mysqli_query($conn, "INSERT INTO USERS VALUES (
'{$id}', '{$username}', '{$email}', '{$passwd}', '{$date_created}', '{$last_login}', '{$status}'
)");
// verify the user's account was created
$query = mysqli_query($conn, "SELECT * FROM users WHERE username='{$username}'");
if (mysqli_num_rows($query) == 1){
/* IF WE ARE HERE THEN THE ACCOUNT WAS CREATED! YAY! */
$success = true;
}
else
$error_msg = 'An error occurred and your account was not created.';
Final touches for the Register Page
Now with our entire register.php code written, we can view it from the web browser. You can even test it out and create your own account on your new register page!
How to Make a User Login Page for Member System
Once you have registered account on your site, you need a way to login. Using some fancy sessions in php, we can allow any user to login using their username and password to gain access to a members only area or even exclusive content.
So now that you have created your registration page and an account, we can create the login page. The code is going to look pretty similar to the register page. Nearly identical actually. We are going to connect to the database, check to see if a user is already logged in, see if they have clicked the login button, show the page header, then the error message, and then the login form. See, identical. But before we get to the code you need to understand how we are going to track the user login. Using sessions!
Sessions and How They Work
Sessions in php are special cookies that will act like variables. It allows us to carry data from page to page on behalf of the users viewing the our websites, without any interaction from them required. The more common ways to use sessions is a login system or even a shopping cart for an online catalog. For a login system, the idea is that you store a piece of data unique to the user in the session after they login, say the unique user id for their specific account. Then in our code we check to see if a session is active and if so get that user id from the session variable. We can then compare that to our database and pull any data we want for the user, say more profile or account information.
The $_SESSION variable will store any current session info for the user viewing the page. It acts like if their is form data we are retrieving from the $_POST variable, or even $_GET. Except, we set the data ourselves though the code and without the need for user interaction. The way that I typically track whether or not the user is logged in is by storing the user id and username in the session. Then if I check to see if they are both set, then I know a user is logged in. If either is NOT set then we know the user has not logged in, and we can display certain information to them accordingly. I also usually do this check at the top of the file or script, and based on the result redirect the user to a different page (say the login page if they are trying to look at member only information). You can really do what ever you would like though. It’s great!
Let’s get into our login code now!
Like I said before about the login and register page being identical, we can follow the same outline for the login page. There is just a little less code. We are even doing most of the same checks against the database. We are really just changing what our code is going to do based on the database results. Just in case you forgot, here is the outline again, this time for the login page:
<?php
// connect to the database
// check for a user being logged in
// process the login form data
?>
<html>
display a header
display the error message (if there is one)
display the login form
</html>
Login Page Front End Display
Our front end for the login page is going to use the same header and code to see if an error message is set. The only thing that really changes is the success message the user would see once they successfully logged in.
<h1>member system tutorial - login</h1>
<a href="./index.php">Home</a> |
<a href="./register.php">Register</a> |
<a href="./login.php">Login</a>
<hr />
<?php
// check to see if the user successfully created an account
if (isset($success) && $success = true){
echo '<font color="green">You have logged in. Please go to the <a href="./index.php">home page</a>.<font>';
}
// check to see if the error message is set, if so display it
else if (isset($error_msg))
echo '<font color="red">'.$error_msg.'</font>';
?>
For the login, we are going to allow users to login using their username and password. So if we create a simple form with a text box for each of those and a login button, we are good to go!
<form action="./login.php" method="POST" name="loginForm">
<table>
<tr><td>Username: <font color="red">*</font></td></tr>
<tr><td><input type="text" value="" name="username" size="35" /></td></tr>
<tr><td>Password: <font color="red">*</font></td></tr>
<tr><td><input type="password" value="" name="passwd" size="35" /></td></tr>
<tr><td>
<input type="submit" name="loginBtn" value="Login" />
<font color="red">*</font> = required fields
</td></tr>
</table>
</form>
Things to note are the names of the text boxes and the login button. Using the names here (of username, passwd, and loginBtn respectively), we can use php code to see if the button was clicked and also get the text the user enter into the other fields.
Login Page Back End Script
We need to connect to the database and check to see if a user is logged in. If they are logged in, then we are going to redirect them to the home page. Because why would they need to see the login page if they have already logged in? You might recognize the above code because it is exactly the same as the top of the register.php file. That’s because we are doing the exact same check in the login script as the register script.
<?php
// include our connect script
require_once("connect.php");
// check to see if there is a user already logged in, if so redirect them
session_start();
if (isset($_SESSION['username']) && isset($_SESSION['userid']))
header("Location: ./index.php"); // redirect the user to the home page
?>
Like before on the register page, we are going to see if the user clicked the login button by checking for the existence of the form element in the $_POST variable. If we find the login button $_POST then the user has clicked the button, in which case we want to process the form data. If it does not exist, then we don’t need to do anything other than display the login form to them.
// check to see if the user clicked the login button
if (isset($_POST['loginBtn'])){
// get the form data for processing
$username = $_POST['username'];
$passwd = $_POST['passwd'];
// make sure the required fields were entered
if ($username != "" && $passwd != ""){
// next code block
}
else
$error_msg = 'Please fill out all required fields.';
}
Since we named our text boxes username and passwd, we can use those names as array keys in $_POST to get the info the user entered. Then we need to make sure their is actual text in them is not empty. How silly would it be if we let a user login with a blank username. Just silly!
Once we have the username and password from the user, we need to make sure the username exists in the database. By doing the simple query below, we can do just that. If one record is found, then one account with the supplied username exists. Now we need to verify the user entered the correct password. After getting the record returned and storing it in the $record variable, we need to encrypt the password in the same way we did in the register script. If you don’t use exactly the same encryption method, then a different password hash will be returned for the same password. So as far as our code will see, the wrong password was entered and the user can’t login. And nobody wants that!
// query the database to see if the username exists
$query = mysqli_query($conn, "SELECT * FROM users WHERE username='{$username}'");
if (mysqli_num_rows($query) == 1){
// get the record from the query
$record = mysqli_fetch_assoc($query);
// encrypt the user's password
$passwd = md5($passwd);
// compare the passwords to make sure they match
if ($passwd === $record['password']){
// make sure the user has activated their account
if ($record['status'] == 1){
// next code block
}
else
$error_msg = 'Please activate your account before you login.';
}
else
$error_msg = 'Your password was incorrect.';
}
else
$error_msg = 'That account does not exist.';
Notice that we are using three equal signs (that’s “===”) to compare the password hashes? This is so the two strings are compared not only on a character to character basis, but our code will also take into account and variations in capitalization. That means that the code wont think “hello” and “HeLLo” are the same password. Next we are checking the account status. If you remember back to the user registration tutorial, we set a default status code of 1 (one) to new accounts, making it so we can login immediately. We could have a status of 0 (zero), which would be an account that needs to be activated, or even 2 (two), for one that has been disabled by an admin. So we perform a simple check to make sure the status code is 1 (one), and if so then let the user login.
Once we have done all of our checks to make sure the user is able and eligible to login, we can create our session variables. We can also create a time stamp using time() since our member system has a last login tracker.
// update the last_login tracker
$last_login = time();
mysqli_query($conn, "UPDATE users SET last_login='{$last_login}' WHERE id='{$record['id']}'");
/* IF YOU GET HERE THE USER CAN LOGIN */
$_SESSION['username'] = $record['username'];
$_SESSION['userid'] = $record['id'];
$success = true;
// redirect the user to the home page
header("Location: ./index.php");
Using a quick UPDATE query, we can update the last_login field in the user’s database record and store the new time stamp of $last_login, but only for the specific user who is logging in. We then store our session data. We are creating two session variables with the names of username and userid, and storing their respective data from the $record variable. Once this session data is set, the user is officially logged in! Then we set our $success variable to true and auto redirect the user to the home page.
Quick Tip: If you have any typos in your query, you may just update every single user’s last_login data. This wouldn’t be a big deal here, but say you had a similar typo in a query to update an email address or a password. Then every user might end up with the same email or password. And that’s not a good day for anyone! If you want to learn more about some cool database operations, check out my database operations tutorial. I go over each of the major types of database queries you will need to operate and maintain a good web site.
Put it all together and see what it all looks like…
Now you have completed the code for your login page. You can open your web browser and check out the page and even login! I will note that since we have not gotten to the email activation part of the tutorial, I have manually set my account status code to 1 (one) using phpMyAdmin. This way I was able to sign in without having to activate my account by the normal means. How to Create a Logout Page for a Member System
After we are able to login we need to be able to logout. The two pages are like ying and yang! Not to mention allowing user to perform special tasks or access exclusive member only content. Without it, their might not be any reason to register on your web site. But don’t worry, it can be coded in only a few minutes.
The Logout Script for Our Member System
Our logout script will be so simple that it will just have a few lines of php code. Nothing to display to the user. The reason for that is because the whole purpose of it is to end the session that we created on the login, and then redirect them to the home page. And if the user is not logged in we can redirect them to the login page. That’s it. Simple and nice!
<?php
// verify the user is logged in
session_start();
if (isset($_SESSION['username']) && isset($_SESSION['userid'])){
/* IF YOU ARE HERE THEN THE USER IS LOGGED IN, AND WE CAN LOG THEM OUT */
session_destroy();
// redirect to the home page
header("Location: ./index.php");
}
else
header("Location: ./login.php"); // redirect the user to the login page
?>
We are first going to use the usual check to see if a user is currently logged in. If they are not then we will redirect them to the login page because this page is sort of a member only page if you think about it. If their is a user logged in, then we can use the session_destory() function to kill their session and delete their $_SESSION data. This one function is all we really need on the logout script but it is nice to add some flare sometimes, right? Once their session has been destroyed, we just redirect them to the home page. That is it. Such a simple script, you have got to love it!
How to Create a Members Only Area for our Member System
For the purpose of this tutorial, our members only area is just going to be our home page. The code will check to see if a user is logged in and display them different content based on their login status. We will even show them more useful navigation links based on their login status. Once they login, the user will no longer see “register” and “login” links. But instead will see a “logout” link. Let’s get to it!
<?php
// include our connect
require_once("connect.php");
// check to see if there is a user already logged in
session_start();
if (isset($_SESSION['username']) && isset($_SESSION['userid']))
$LOGGED_IN = true;
else
$LOGGED_IN = false;
?>
We are using a slight variation on the normal user login check. Instead of redirecting users as needed, we are setting a boolean variable based on their login status. We set the $LOGGED_IN variable to true if they are logged in and false not. We can then do a very simple check to this variable to see if the user is in fact logged in or not, the display the content accordingly.
Display a different navigation for Members ONLY
The navigation will a pretty similar setup. The only thing that will change is the actual links that will be displayed.
<h1>member system tutorial - User Home</h1>
<a href="./index.php">Home</a> |
<?php
// display the user aware navigation links
if ($LOGGED_IN == true){
echo '<a href="./logout.php">Logout</a>';
}
else{
echo '<a href="./register.php">Register</a> | ';
echo '<a href="./login.php">Login</a>';
}
?>
<hr />
Using our nifty $LOGGED_IN variable, we display either a “logout” link or the usual “register” and “login” links.
<?php
if ($LOGGED_IN == true){
echo 'Hello '.$_SESSION['username'].', how are you today?<br /><br />';
// get the user's account information from the database
$query = mysqli_query($conn, "SELECT * FROM users WHERE id='{$_SESSION['userid']}'");
if (mysql_num_rows($query) == 1){
$_USER = mysqli_fetch_assoc($query);
echo 'Your account was created on: <u>'.date("M d, Y", $_USER['date_created']).'</u><br /><br />';
echo 'You last logged in at <i>'.date("g:i A (T)", $_USER['last_login']).'</i> on <i>'.date("M d, Y", $_USER['last_login']).'</i><br />';
}
else
echo 'Unable to load your account information. Please logout and log back in.';
}
else
echo 'Please login to your account to see some super cool stuff!';
?>
Using a simple if statement, we display different page content to the user. If a user is not logged in, we just tell them to login. But if they are already logged in, then we are going to display them a greeting and then query the database to get some more information about, other than the user id and username that is stored in the $_SESSION. For this example, I am just going to display the date they created their account and when they last logged in. Nothing too fancy but it gets the message across.
Full Member System Created from Scratch
At this point, we have created a entire member system! One that allows users to register for an account and then login immediately. We also learned how to display different content based on the user’s logged in status. These are some pretty simple tasks after you see it done one or twice, but they are arguably the most important to understand when it comes to a modern web site.
Just watched your tutorial on how to build a custom search engine using PHP and MySQL…Dude,you just made me wanna stop learning web dev…I felt as though I know nothing…
But that was very good though…I’d love for you to be my mentor in Web dev, and perhaps all things finances…lol
WOW! Thanks! Don’t worry, you’ll get there too! It just takes time and doing lots of little projects to build up your skills. Then do some bigger projects to round them all out.
This is the perfectt blog for anybody who hopes to find out about this topic.
You definitely put a brand nnew spin on a topic which has been discussed
for decades.Wonderful stuff, just excellent!