Left Quote    Copy from one, it's plagiarism; copy from two, it's research.
- Wilson Mizner    
Right Quote
[login] | [Register]

Complete Members System

by: bs0d
Page: 1 of 9
(View All)


Nearly every website allows you (the visitor) to become a member of the site you're visiting. Typically, one will register a desired username, and setup a password, then fill out a bit of information to stock a profile, like: location, interests, etc. and you're done. You can then access parts of the site that were once restricted, participate in forum discussions and cast your vote on polls - you get the idea. But how is that done? How do they distinguish between members? How can I do that with my site? Read on and you will learn how to allow visitors to register as members, and allow them to login/logout of your website.


Just like anything else, a few requirements exist before this can be accomplished.
  1. PHP - This means the company/website that provides you webspace (your host) has PHP installed on their server. Or, download and install PHP for free if you're running your own server. Here is a link:
  2. MySQL database - This means the company/website that provides you webspace (your host) has MySQL database installed on their server. Or, download and install MySQL for free if you're running your own server. Again, here is a quick link:
  3. phpMyAdmin - Not required, but you will be creating tables in your database, and this tool makes it much easier! Just like the others, free download heres a link:
  4. Proper Design - You will be entering code that needs to appear on every page of your site, so to make this simpler on your part, your site should be setup where everything is broken up like: page_header, page_sidebar, etc. If you're lost, read this tutorial: Site Design Made Simple.
  5. PATIENCE!!! - It almost never works the first time you set it up. Find your errors and go from there. I will guide you through as best as I can, but in the end if there is something you cannot fix or find an answer for, try the Forums and if I cannot help you, someone else can.


Here is an outline of the steps we will take to prepare for the script and so on.
  • Create members table in database - you can use phpMyAdmin and create the table by hand, or import SQL, which I will provide.
  • Create a register script - If you've going to have members, you need to allow them to signup. When they do, their information will be stored in the members table.
  • Create a login page - At this point, we create a page that will log them into the site and check their username and password aginst what is stored in the database. Upon success, a cookie will be applied and the user will be redirected to the main page.
  • Modify your page_header - In your page_header code (like from the Site Design Made Simple tutorial) we will be adding code to check for the cookie to see if they're logged in.
  • Logout - Somewhere on your website, you can display their logged in status with variables we will setup, but also display a link to logout page, that will log them out. This page will destroy the session, set the cookie backward and take them back to the main page. If they're not logged in, we can display a login link and "welcome guest" or something similar.
Just to remind you, this can easily be combined with other scripts/tutorials I have setup that deal with users on your website, like Users Online and Comments Script. If you get the concept of these tutorials, it wont take much to do this.


To get things started off, our first step is designing the table that our data will be stored into. We will be storing information so that members can login to the site. So we create a table "members" - Next we need something to uniquely identify each member (other than username), so we will have a column called "user_id" - The other two columns we will use are "username" and "user_password". You might want to add more to yours, like location, interests, etc. This is just a basic example.

Listed below is the SQL code to create the table. You can run that in phpMyAdmin to create the table, or just create the table using the design I will now explain. The user_id column will auto increment, meaning each time a member registers, their unique id will automatically be assigned. the username column is set to varchar(25), meaning that the max length of the character string (username) cannot exceed 25; The same applies to the user_password column at 32. User email field can be as long as 255. You can change those to whatever you wish, that is just the way I set them up.


Now we discuss the register script. This is the form that visitors will fill out if they decide to become a member. The form is basic HTML, but we use php to analyze and store the values in the members table. We need to decide what will appear on the form.
  1. username field: Indicate the max length (25 chars) and minimum, and possibly what values are accepted (A-Z, 0-9) - whatever you decide. We can create an array of rejected characters, search the username value to see if it contains any of these values, and display an error if a match is found. Check the length to see if its too small, show an error if its smaller than the length you decide on.
  2. password field: Indicate max length (32) and minimum, and just like the username field, the characters that would be not accepted. Can search this value the same as explained above as well. Also can check the length of the password entered and if its too small, display an error.
  3. verify password: This is an optional field, but I would recommend it. This ensures that the user is aware of exactly what he or she entered. We will check if this field is identical match to the password field. If they do not match, display an error.
  4. email address: Allow them to enter their email address. Could be optional, or it could be required. You could use this to possibly inform them of updates to the site, or a newsletter. Therefore, it might be handy to know that the email address they entered, is valid. To verify that, send an activation code to the email specified, make them follow a link and enter the code. If the membership is activated, then you know they put in a real email address, and have access to it.

What you want to do is try to eliminate all of the errors, so that what you get in the database is exactly what you want, and what the new member wants. You have to think out all possible senarios, and check each with code to hault execution if that condition is met.

Its also nice to know that 90% of your registered members are actually members, and not a form of spam. Thats more reasoning behind something like email activation, and also incorperating something like an image validation (Enter code appearing in this image). Spam bots cannot see what dynamically generated in the image, so it must be a person genuinely interested that is wanting to sign up.

This is BASICALLY all you need. Everyone that reads this should explore adding more to what I have shown so far. All you need to do is add the appropriate columns to the table, and create a field in this script. Some things you could add are: Registration date, ICQ #, MSN id, Yahoo ID, Interests, Location, etc.


Now that we've got an idea of what we need, lets put words to code. First thing's first, we need to connect to the database, because we will be adding a user to the member table. Instead of rewriting the same code over and over for each script to connect, I just put that code in a file, and require it in each script I need to use it, like this:

*Note: If you do not know what needs to be included in this file to make a proper connection to the database, then view this code sample: Database Connection

We're going to be using sessions for the username, login status, etc. We will get to this later, but in our page_header code, sessions have already been started by executing the session_start(); function. In our login script, we'll the create session variables and assign values to them. For login status, we'll apply that to: $_SESSION['logged_in']. The value will be zero if not logged in by default, and one if logged in. Lets check if the visitor is logged in, if they are - then they have already registered, and do not need to be able to visit the register page again. With that being said, we can just redirect them to the home page. Observe code below:

Notice the open } else { at the end. This is because, if the user is not logged in, we're going to carry on with the script. The first thing to assume is that the submit button has been pressed. Basically, going from the end to the start, because the very end of the script will be to display the form. So, lets go though some more code.


This says, if submit button was pressed to execute all code below. Then we check if any value is in username field, if not - kill script and alert the error.

Next thing I chose to do was to declare unwanted characters, and scan the username to see if the potential member chose any of these for their desired username. Below is the code:

$junk is an array of desired invalid characters. In $len, I check the length of the entered username. Then, I basically strip out the invalid characters from the entered username. And finally, I check if the length of $len (starting length) is not equal to the new length (stripping characters out if they exist). If they're not equal, characters were stripped, and I kill the script, and inform the visitor of the error.

The next step I chose was to take the valid username entered, and see if it is already taken. See code below:

Query the members table where username from table = entered username. The if condition checks if $q3->username (from database) is equal to the desired username ($_POST['username']). If there is a match, someone already has the username, and and error will be displayed.


Next in line is the password and verify password fields. It is important that they know what their password will be, and that the verify password field matches the password field. So in the code, we check exactly that. Take a look:

Four tests here: check if password field is empty, check if verify password field is empty, check if password is equal to verify password, and check if the password is less than six characters in length. If any of these conditions are met, an error will be displayed. Any password that passes through this, is considered to be acceptable for insertion. We dont check the password for oddball characters, because having them will actually increase the strength of their password.


Now that we're this far, we are ready to add a member. This tutorial only checked the username and password (most important), but you might want to take it a step further to see if there is a valid email address or something else. Below is the code to insert the new member:

Basic insertion query: inserting into members table, then the column fields of the table to insert into, and finally the values to put into the column fields of the member table. Tha values are from the form the user filled out, and are accessed by $_POST method. Notice md5() function on the password. This is an encryption, so that the password is more secure and safe in the database, than just the password itself. In the login script, we will md5 the entered password and check it aginst the md5 password in the database. They will match if the entered passwords are the same.

Last step, is to display the form. Basic HTML form is all you need. Im sure more advanced ways exist, but we'll go with what we know works for now.

Thats an example of what you might use (above). Form action is set to PHP_SELF and method is POST. The name of the input boxes will be represenative of the $_POST value (input id = username, then $_POST['username'] is the value for values in that input box).

That is the end of the registration script. If everything was a success, the registration successful message will appear and your member can now login. So, we must create a login script for them next!


If you have followed the tutorial so far, the members table has been made in the database, and a registration script has been coded where members may signup and the values they enter on the page will be inserted into the members database.

This login script will allow them to enter their username and password. Our script will detect that there is an existing username matching what they entered, and check the password (md5()) aginst the password on record for that username. If login is successful, a cookie will be applied (if desired), and redirect them to the main page. If an error is encountered, prompt user appropriately.

Lets go:

Ok, the first thing you see is ob_start(); If you're unfamiliar with ob_start, see It has to do with output before headers and such so this way its buffered instead. Could boil down to the way the error messages are setup. If it has to do with empty or fields or not enough characters in a field, javascript is a nice client side solution. But, this is just an example and we're just presenting the basic idea, remember.

Next, you will see that just like the registration script, we needed to require the database connect file beause we will be communicating with the database.

The next bit of code checks if the user is logged in. Notice the session variables.These are variables that we set when a login is successful, along witha few others you will soon see. So we are checking the values of these variables to see if the user is already logged in. If so, there is no reason for them to be able to visit the login page. So, instead we will just redirect them to the main page.

Lets carry on...

The code above goes directly under the last block of code we discussed. We are opening the if condition that checks if the submit button was pressed on the form. The end } for this block will be followed by the else condition to show the form (submit button not pressed). So everything in between will analyze what we need when the button is pressed.

So first thing is first, if the username or password field is blank, prompt an error. The next part checks if the visitor selected to "remember me" or not. If so, apply cookie. This is achieved with the setcokie() function, which uses this format:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )

Taken from


Simply done, $get_user is a mysql query to the database that will select a username with the values you provided. If the query is not successful, a match was not found in the database. so either it was the username field, or password.


This is the code that will follow the code from above. If the script executes a successful query, then a member name and password matched. We can now apply session variables to recognize them - and immediately redirect to the main page (or whatever page you decide).

We are assigning three session variables. A logged in status (1 = logged in, 0 = not logged in), username and password. These sessions will last until the browser is closed. session_write_close(); is not required, but will force the session data to be saved before the browser changes to the new page when we call the header function.


Now the form must be shown for them to login. Our first condition checked if the submit button was pressed. All code above was to be executed based on that condition. If that condition fails, we display the form. That is what we do below.

Notice the else condition opening bracket before the html form, and the closing bracket at the end. Else is saying "show the form because the submit button was not pressed." Nothing is special about the form and table, basic html - you can church it up as you like. This is the bare bones to get the job done. We will now cover the code in the page header.


If you've followed along with the tutorial (as you should), you know that when I say page_header, I am refering to code that is executed on every page of your site. Earlier we mentioned that the session_start( ); function was called in the page_header code. Again, it is important to know that one cannot access $_SESSION variables unless this is called FOR EACH SCRIPT. So, thats why we are plugging it in to the page_header code (executed on each page) so that we dont have to worry about it anymore. session_start( ); also allows you to continue a session from page to page.

After this, we also connect to the database. Here is the beginning of our code:


Now we've got that out of the way. We can get down to business. In our page_header code, we need to check if a cookie has been set using our login script if the user selected "Remember me". If the cookie is detected, then we need to see if the username and encrypted password they saved in the cookie match with what is in the database. If so, we can plug in the values from the cookie (user, pass) into $_SESSION variables, and set their logged in status to = 1.

The first condition says, if session variable logged_in is not equal to one, and a cookie is set with the name "login_cookie" then execute code below. Code below uses the list(); function, which grabs multiple variables in one pass. We use the explode(); function to seperate the values stored in our cookie (accessed by $_COOKIE['login_cookie'];) where [] is detected. The first part is stored in $user, the second part is stored in $pass (via the list function).

With $user and $pass in hand, we can query the database members table to see if a user match is found (where username = username from cookie). Next condition states, if 1 row result is returned (all their should be), then the result from the query is put in the $passw variable. And finally, our last condition tests if the password from the query matches the password from the cookie, then the user is validated. We then apply the session variables for logged in status, username and password.


Ok, just we checked if a cookie was set, and logged them in if one existed. what if a cookie did not exist (they did not choose "Remember me"), but they signed in? We can check if the session variables are set or not - they were set at login, so they should be! So if they are not, they did not sign in or a login was not successful.

This is all we would need. Basically, from the code above - we check if the session variables for username and password are NOT set. If they are, then nothing is done because they are already set. If they are not, then we set $_SESSION['logged_in'] to 0, and our $user variable to "Guest." If everything went to plan, we should be able to echo $user and the member should see their username.


Once your members are able to sign in, they should have the option to sign out. Create a file called "logout.php" and if a member is logged in, display this link so that they may access it. Below is the code used to successfully logout a user:

As you see, we set $_SESSION['logged_in'] to equal 0, because it is set to 1 when they are signed in. Next, notice we are setting another cookie. Notice though, the setcookie( ); function. We are not setting a cookie, but deleting the one specified. This is achieved by setting a negative time. In this example I used time() - 60. This will successfully delete the cookie that was set if the user chose "Remember me." Finally, a call to session_destroy(); will delete all of the data that is in the current session. Afterwards, we use header( ); to automatically reload us to a desired page. In most instances, the index or main page of your site if you so choose.


Well, Kudos to those who actually read through the entire tutorial! If you did, you should be able to grasp the concept pretty easy. I didn't care how long the tutorial would turn out to be. I wanted to make sure that everyone who read through would be able to have a good start at building a member system for their own website. I did not write the tutorial in one setting, this is probably a couple of months worth of 10 minuts free time here and there. So if any part seems repetitive, irrelevant or off topic in any way just let me know and I can make revisions.

In this tutorial, code for scripts are broken up into alot of parts. So here is the full code for each script. If anyone has any questions, feel free to join discussion in our Forums!


-bs0d |

Members Table (sql):

Registration Script:

Login script:

Page_header code:


1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  
Next »


  Subject: "Member Pages" Date: Jan 30 2008 at 9:56 pm    
Thanks for all the time you put into this tutorial which I imagine would have been a lot !

I've followed this tutorial and set everything up as you explain, but I don't understand how to actually use it. Please could you show me how to set up a page in which only someone who has logged in, i.e. a member, can access?

Thanks for your time =]
  Subject: "page_header code" Date: Jan 30 2008 at 9:58 pm    
Also, what do you do with the page_header code? Should that be saved as a different .php file or should that be included in every page above everything else?

Thanks =]
  Subject: "Confusion..." Date: Mar 17 2008 at 9:34 pm    

Are so confusing you dont even tell us what to do or what files to make, you pretty much just give us the code.

Can you please make it more clear of what we have to do.
  Subject: "re: Confusion..." Date: Mar 18 2008 at 1:10 pm    

Chrisn07 : I would make the page_header code a file of its own ( p) and include that (at the top) of each page you want to recognize members on. As the beginning of the article indicates, check out the 'Site Design Made Simple' - and your life will be much easier in doing this.

uzi614: Are you serious? Did you read the, "Creating A Register Script - Design" part? It's a basic HTML form - The article is about the script, not the HTML. As you point out, even that is provided, however.

And just to clarify - the register script is register.php (you can actually name it anything you want) just reference to it accordingly. This is a table that a user fills out (HTML form) and when the user clicks submit, then the PHP code that I covered makes sure the input by the user is legit.

The comments section of the site is not the proper channel to address and diagnose script details and functionality. If you have an issue you want to discuss, start a topic in the appropriate directory of the forums< /a> and we can break down each block of code if you need.
  Subject: "What am i doing wrong?" Date: Mar 23 2008 at 6:40 pm    
Am i doing something wrong?

I keep getting this error: Warning: session_start() [function.sessi on-start]: Cannot send session cache limiter - headers already sent (output started at /home/virtuals/ public_html/ind ex.php:7) in /home/virtuals/ public_html/pag e_header.php on line 3

The code of my page_header.php =

session_start( );
require_once($_ SERVER['DOCUME NT_ROOT'].'/d b_connect.php' );

if ($_SESSION['lo gged_in'] != 1 && isset($_COOKIE[ 'login_cookie '])) {
list($user, $pass) = explode('[]', $_COOKIE['logi n_cookie']); $qu = mysql_query(&q uot;SELECT `user_password` FROM `members` WHERE `username` = '".addsl ashes($user).& quot;'") ;
if (mysql_num_rows ($qu) == 1) {
$passw = mysql_fetch_obj ect($qu);
if ($passw->use r_password == $pass) {
$_SESSION['log ged_in'] = 1;
$_SESSION['use rname'] = $user;
$_SESSION['pas sword'] = $pass;

if(!isset($_SES SION['username ']) && !isset($_SESSIO N['password'] )) {
$_SESSION['log ged_in'] = 0;
$user = "Guest&q uot;;

and the code of my index.php ( I just had it for a test )

<html> <head>
<title>Ju statest</tit le>
</head> <body>

<?php include(" page_header.php "); ?>

</body> </html>

Can someone tell me what i am doing wrong? I have a db_connect.php file, login.php file, register.php file, and logout.php file. What am i doing wrong???
  Subject: "re: what am i doing wrong?" Date: Mar 24 2008 at 4:32 pm    


Remove ob_start(); from the scripts, and place it in your HTML file even above <HTML>, like this:
<? ob_start(); ?>
<title>Ju statest</tit le>
</head> <body>

<?php include(" page_header.php "); ?>


  Subject: "php include inside of a div on in i..." Date: May 12 2008 at 9:14 pm    
is it possible to place the php include inside of an html div so that i can include the login on all of my pages? I have looked all over the web and I have not found any answers?
  Subject: "Include" Date: May 16 2008 at 1:21 am    

I dont see why not... unless im understanding the question wrong.
  Subject: "someone reposted this" Date: Jul 16 2008 at 4:47 am    
Eboracom's version< /a>

It says it can't find the author and to contact them, but they don't have a contact page.

Iunno if it has been pointed out before, so I just decided to comment it. =]
  Subject: "something wrong with tagging" Date: Feb 02 2009 at 6:06 am    
I am having a problem with defining the array of invalid characters. I am getting errors like "expected ')' on line 20." It happens with the following tags: '[' , ']' , '/' (and more). I think it may be because I'm working on a mac and the quote marks are confusing the code. If I remove the function to verify the username for invalid characters, everything works great. Anyone know a way to avoid this error?
  Subject: "bugs" Date: Oct 11 2009 at 3:57 pm    
In the junk array in the register section, the backslash cancels the single quote. Is this a suitable fix?

//array of invalid characters
$junk = array('.' , ',' , '/' , "\" ; , '`' , ';' , '[' , ']' , '-',
'*', '&', '^', '%', '$', '#", '@', '!', '~', '+', '(', ')',
'|', '{', '}', '<', '>', '?', ':', '"', '=');

Another problem with the register part is that if the username is over 25 characters (or whatever limit it is), the script will check the entered username with the database ones, but not find one as they are truncated, then it will add that username, and it could be a duplicate.
If that didn't make sense, then here's an example:
when the username thisusernamehas overtwenty5char acters is first registered, it gets stored as thisusernamehas overtwenty. If any username starting with thisusernamehas overtwenty is registered, it will pass the check, but then be stored as thisusernamehas overtwenty in the database too. Some sort of length validation or truncating bit is needed.

Also, why does the userid start at 60?

And one last thing. I have the register, login, etc bits as separate include files (with header and footer ones above and below it). When the script is succesful, it shows the footer.php code, but when it isn't and dies, it kills everything, meaning no footer. Is tehre a way to get past this?
  Subject: "Log In Script" Date: May 11 2014 at 8:58 pm    
This is a great start for me. I am new to PHP and HTML but have been tasked to build a website for my alumni association which is in Jamaica. I have been using Weebly Drag&Drop to build my site but it does not have a members sign-in function. I have been reading tons of blog and found this very interesting. I may have to read it several times but I believe in it.
Thanks for creating such a great document with simple instructions. I look forward to reading other blogs supporting this function. I have already created my DB and 'members' table with 5 fields. Looking forward to putting all the script sections together; register section and login.
Thanks again.
You Must be logged in or a member to comment.

Tutorial Stats

Tutorial Stats

41 Total Comments
4.8 Rating of 5 (5 Votes)


Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article



· Simple PHP Tutorial
· One File Website
· Pagination with PHP
· Building a Comments Script
· Variable Scope

"" Copyright © 2002-2017; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank