Advertisement
  1. Code
  2. PHP

User Membership With PHP

Scroll to top
Read Time: 15 min

A tutorial for the very beginner! No matter where you go on the Internet, there's a staple that you find almost everywhere - user registration. Whether you need your users to register for security or just for an added feature, there is no reason not to do it with this simple tutorial. In this tutorial we will go over the basics of user management, ending up with a simple Member Area that you can implement on your own website.

Introduction

In this tutorial we are going to go through each step of making a user management system, along with an inter-user private messaging system. We are going to do this using PHP, with a MySQL database for storing all of the user information. This tutorial is aimed at absolute beginners to PHP, so no prior knowledge at all is required - in fact, you may get a little bored if you are an experienced PHP user!

This tutorial is intended as a basic introduction to Sessions, and to using Databases in PHP. Although the end result of this tutorial may not immediately seem useful to you, the skills that you gain from this tutorial will allow you to go on to produce a membership system of your own; suiting your own needs.

Before you begin this tutorial, make sure you have on hand the following information:

  • Database Hostname - this is the server that your database is hosted on, in most situations this will simply be 'localhost'.
  • Database Name, Database Username, Database Password - before starting this tutorial you should create a MySQL database if you have the ability, or have on hand the information for connecting to an existing database. This information is needed throughout the tutorial.

If you don't have this information then your hosting provider should be able to provide this to you.

Now that we've got the formalities out of the way, let's get started on the tutorial!

Step 1 - Initial Configuration

Setting up the database

As stated in the Introduction, you need a database to continue past this point in the tutorial. To begin with we are going to make a table in this database to store our user information.

The table that we need will store our user information; for our purposes we will use a simple table, but it would be easy to store more information in extra columns if that is what you need. In our system we need the following four columns:

  • UserID (Primary Key)
  • Username
  • Password
  • EmailAddress

In database terms, a Primary Key is the field which uniquely identifies the row. In this case, UserID will be our Primary Key. As we want this to increment each time a user registers, we will use the special MySQL option - auto_increment.

The SQL query to create our table is included below, and will usually be run in the 'SQL' tab of phpMyAdmin.

1
CREATE TABLE `users` (
2
`UserID` INT(25) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
3
`Username` VARCHAR(65) NOT NULL ,
4
`Password` VARCHAR(32) NOT NULL ,
5
`EmailAddress` VARCHAR(255) NOT NULL
6
);

Creating a Base File

In order to simplify the creation of our project, we are going to make a base file that we can include in each of the files we create. This file will contain the database connection information, along with certain configuration variables that will help us out along the way.

Start by creating a new file: base.php, and enter in it the following code:

1
<?php
2
session_start();
3
4
$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ

5
$dbname = "database"; // the name of the database that you are going to use for this project

6
$dbuser = "username"; // the username that you created, or were given, to access your database

7
$dbpass = "password"; // the password that you created, or were given, to access your database

8
9
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
10
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
11
?>

Let's take a look at a few of those lines shall we? There's a few functions here that we've used and not yet explained, so let's have a look through them quickly and make sense of them -- if you already understand the basics of PHP, you may want to skip past this explanation.

1
session_start();

This function starts a session for the new user, and later on in this tutorial we will store information in this session to allow us to recognize users who have already logged in. If a session has already been created, this function will recognize that and carry that session over to the next page.

1
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
2
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

Each of these functions performs a separate, but linked task. The mysql_connect function connects our script to the database server using the information we gave it above, and the mysql_select_db function then chooses which database to use with the script. If either of the functions fails to complete, the die function will automatically step in and stop the script from processing - leaving any users with the message that there was a MySQL Error.

Step 2 - Back to the Frontend

What Do We Need to Do First?

The most important item on our page is the first line of PHP; this line will include the file that we created above (base.php), and will essentially allow us to access anything from that file in our current file. We will do this with the following line of of PHP code. Create a file named index.php, and place this code at the top.

1
<?php include "base.php"; ?>

Begin the HTML Page

The first thing that we are going to do for our frontend is to create a page where users can enter their details to login, or if they are already logged in a page where they can choose what they then wish to do. In this tutorial I am presuming that users have basic knowledge of how HTML/CSS works, and therefore am not going to explain this code in detail; at the moment these elements will be un-styled, but we will be able to change this later when we create our CSS stylesheet.

Using the file that we have just created (index.php), enter the following HTML code below the line of PHP that we have already created.

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2
<html xmlns="http://www.w3.org/1999/xhtml">  
3
<head>  
4
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
5
<title>User Management System (Tom Cameron for NetTuts)</title>
6
<link rel="stylesheet" href="style.css" type="text/css" />
7
</head>  
8
<body>  
9
<div id="main">

What Shall We Show Them?

Before we output the rest of the page we have a few questions to ask ourselves:

  1. Is the user already logged in?
  • Yes - we need to show them a page with options for them to choose.
  • No - we continue onto the next question.
  • Has the user already submitted their login details?
    • Yes - we need to check their details, and if correct we will log them into the site.
    • No - we continue onto the next question.
  • If both of the above were answered No, we can now assume that we need to display a login form to the user.
  • These questions are in fact, the same questions that we are going to implement into our PHP code. We are going to do this in the form of if statements. Without entering anything into any of your new files, lets take a look at the logic that we are going to use first.

    1
    <?php
    
    2
    if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
    
    3
    {
    
    4
    	// let the user access the main page
    
    
    5
    }
    
    6
    elseif(!empty($_POST['username']) && !empty($_POST['password']))
    
    7
    {
    
    8
    	// let the user login
    
    
    9
    }
    
    10
    else
    
    11
    {
    
    12
    	// display the login form
    
    
    13
    }
    
    14
    ?>
    

    Looks confusing, doesn't it? Let's split it down into smaller sections and go over them one at a time.

    1
    if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
    
    2
    {
    
    3
    	// let the user access the main page
    
    
    4
    }
    

    When a user logs into our website, we are going to store their information in a session - at any point after this we can access that information in a special global PHP array - $_SESSION. We are using the empty function to check if the variable is empty, with the operator ! in front of it. Therefore we are saying:

    If the variable $_SESSION['LoggedIn'] is not empty and $_SESSION['Username'] is not empty, execute this piece of code.

    The next line works in the same fashion, only this time using the $_POST global array. This array contains any data that was sent from the login form that we will create later in this tutorial. The final line will only execute if neither of the previous statements are met; in this case we will display to the user a login form.

    So, now that we understand the logic, let's get some content in between those sections. In your index.php file, enter the following below what you already have.

    1
    <?php
    
    2
    if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
    
    3
    {
    
    4
    	 ?>
    
    5
    6
    	 <h1>Member Area</h1>
    
    7
         <pThanks for logging in! You are <code><?=$_SESSION['Username']?></code> and your email address is <code><?=$_SESSION['EmailAddress']?></code>.</p>
    
    8
         
    
    9
         <?php
    
    10
    }
    
    11
    elseif(!empty($_POST['username']) && !empty($_POST['password']))
    
    12
    {
    
    13
    	$username = mysql_real_escape_string($_POST['username']);
    
    14
        $password = md5(mysql_real_escape_string($_POST['password']));
    
    15
        
    
    16
    	$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
    
    17
        
    
    18
        if(mysql_num_rows($checklogin) == 1)
    
    19
        {
    
    20
        	$row = mysql_fetch_array($checklogin);
    
    21
            $email = $row['EmailAddress'];
    
    22
            
    
    23
            $_SESSION['Username'] = $username;
    
    24
            $_SESSION['EmailAddress'] = $email;
    
    25
            $_SESSION['LoggedIn'] = 1;
    
    26
            
    
    27
        	echo "<h1>Success</h1>";
    
    28
            echo "<p>We are now redirecting you to the member area.</p>";
    
    29
            echo "<meta http-equiv='refresh' content='=2;index.php' />";
    
    30
        }
    
    31
        else
    
    32
        {
    
    33
        	echo "<h1>Error</h1>";
    
    34
            echo "<p>Sorry, your account could not be found. Please <a href=\"index.php\">click here to try again</a>.</p>";
    
    35
        }
    
    36
    }
    
    37
    else
    
    38
    {
    
    39
    	?>
    
    40
        
    
    41
       <h1>Member Login</h1>
    
    42
        
    
    43
       <p>Thanks for visiting! Please either login below, or <a href="register.php">click here to register</a>.</p>
    
    44
        
    
    45
    	<form method="post" action="index.php" name="loginform" id="loginform">
    
    46
    	<fieldset>
    
    47
    		<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
    
    48
    		<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
    
    49
    		<input type="submit" name="login" id="login" value="Login" />
    
    50
    	</fieldset>
    
    51
    	</form>
    
    52
        
    
    53
       <?php
    
    54
    }
    
    55
    ?>
    
    56
    57
    </div>
    
    58
    </body>
    
    59
    </html>
    

    Hopefully, the first and last code blocks won't confuse you too much. What we really need to get stuck into now is what you've all come to this tutorial for - the PHP code. We're now going to through the second section one line at a time, and I'll explain what each bit of code here is intended for.

    1
    	$username = mysql_real_escape_string($_POST['username']);
    
    2
        $password = md5(mysql_real_escape_string($_POST['password']));
    

    There are two functions that need explaining for this. Firstly, mysql_real_escape_string - a very useful function to clean database input. It isn't a failsafe measure, but this will keep out the majority of the malicious hackers out there by stripping unwanted parts of whatever has been put into our login form. Secondly, md5. It would be impossible to go into detail here, but this function simply encrypts whatever is passed to it - in this case the user's password - to prevent prying eyes from reading it.

    1
    	 $checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
    
    2
        
    
    3
        if(mysql_num_rows($checklogin) == 1)
    
    4
        {
    
    5
        	 $row = mysql_fetch_array($checklogin);
    
    6
            $email = $row['EmailAddress'];
    
    7
            
    
    8
            $_SESSION['Username'] = $username;
    
    9
            $_SESSION['EmailAddress'] = $email;
    
    10
            $_SESSION['LoggedIn'] = 1;
    

    Here we have the core of our login code; firstly, we run a query on our database. In this query we are searching for everything relating to a member, whose username and password match the values of our $username and $password that the user has provided. On the next line we have an if statement, in which we are checking how many results we have received - if there aren't any results, this section won't be processed. But if there is a result, we know that the user does exist, and so we are going to log them in.

    The next two lines are to obtain the user's email address. We already have this information from the query that we have already run, so we can easily access this information. First, we get an array of the data that has been retrieved from the database - in this case we are using the PHP function mysql_fetch_array. I have then assigned the value of the EmailAddress field to a variable for us to use later.

    Now we set the session. We are storing the user's username and email address in the session, along with a special value for us to know that they have been logged in using this form. After this is all said and done, they will then be redirect to the Member Area using the META REFRESH in the code.

    So, what does our project currently look like to a user?

    Great! It's time to move on now, to making sure that people can actually get into your site.

    Let the People Signup

    It's all well and good having a login form on your site, but now we need to let user's be able to use it - we need to make a login form. Make a file called register.php and put the following code into it.

    1
    <?php include "base.php"; ?>
    
    2
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    3
    <html xmlns="http://www.w3.org/1999/xhtml">  
    
    4
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
    
    5
    6
    <title>User Management System (Tom Cameron for NetTuts)</title>
    
    7
    <link rel="stylesheet" href="style.css" type="text/css" />
    
    8
    </head>  
    
    9
    <body>  
    
    10
    <div id="main">
    
    11
    <?php
    
    
    12
    if(!empty($_POST['username']) && !empty($_POST['password']))
    
    
    13
    {
    
    
    14
    	$username = mysql_real_escape_string($_POST['username']);
    
    
    15
        $password = md5(mysql_real_escape_string($_POST['password']));
    
    
    16
        $email = mysql_real_escape_string($_POST['email']);
    
    
    17
        
    
    
    18
    	 $checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
    
    
    19
         
    
    
    20
         if(mysql_num_rows($checkusername) == 1)
    
    
    21
         {
    
    
    22
         	echo "<h1>Error</h1>";
    
    
    23
            echo "<p>Sorry, that username is taken. Please go back and try again.</p>";
    
    
    24
         }
    
    
    25
         else
    
    
    26
         {
    
    
    27
         	$registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES('".$username."', '".$password."', '".$email."')");
    
    
    28
            if($registerquery)
    
    
    29
            {
    
    
    30
            	echo "<h1>Success</h1>";
    
    
    31
            	echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>";
    
    
    32
            }
    
    
    33
            else
    
    
    34
            {
    
    
    35
         		echo "<h1>Error</h1>";
    
    
    36
            	echo "<p>Sorry, your registration failed. Please go back and try again.</p>";    
    
    
    37
            }    	
    
    
    38
         }
    
    
    39
    }
    
    
    40
    else
    
    
    41
    {
    
    
    42
    	?>
    
    43
        
    
    44
       <h1>Register</h1>
    
    45
        
    
    46
       <p>Please enter your details below to register.</p>
    
    47
        
    
    48
    	<form method="post" action="register.php" name="registerform" id="registerform">
    
    49
    	<fieldset>
    
    50
    		<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
    
    51
    		<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
    
    52
            <label for="email">Email Address:</label><input type="text" name="email" id="email" /><br />
    
    53
    		<input type="submit" name="register" id="register" value="Register" />
    
    54
    	</fieldset>
    
    55
    	</form>
    
    56
        
    
    57
        <?php
    
    
    58
    }
    
    
    59
    ?>
    
    60
    61
    </div>
    
    62
    </body>
    
    63
    </html>
    

    So, there's not much new PHP that we haven't yet learned in that section. Let's just take a quick look at that SQL query though, and see if we can figure out what it's doing.

    1
    $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES('".$username."', '".$password."', '".$email."')");
    

    So, here we are adding the user to our database. This time, instead of retrieving data we're inserting it; so we're specifying first what columns we are entering data into (don't forget, our UserID will go up automatically). In the VALUES() area, we're telling it what to put in each column; in this case our variables that came from the user's input. So, let's give it a try; once you've made an account on your brand-new registration form, here's what you'll see for the Member's Area.

    Make Sure That They Can Logout

    We're almost at the end of this section, but there's one more thing we need before we're done here - a way for user's to logout of their accounts. This is very easy to do (fortunately for us); create a new filed named logout.php and enter the following into it.

    1
    <?php include "base.php"; $_SESSION = array(); session_destroy(); ?>
    
    2
    <meta http-equiv="refresh" content="0;index.php">
    

    In this we are first resetting our the global $_SESSION array, and then we are destroying the session entirely.

    And that's the end of that section, and the end of the PHP code. Let's now move onto our final section.

    Step 3 - Get Styled

    I'm not going to explain much in this section - if you don't understand HTML/CSS I would highly recommend when of the many excellent tutorials on this website to get you started. Create a new file named style.css and enter the following into it; this will style all of the pages that we have created so far.

    1
    * {
    
    2
    	margin: 0;
    
    3
        padding: 0;
    
    4
    }
    
    5
    body {
    
    6
    	font-family: Trebuchet MS;
    
    7
    }
    
    8
    a {
    
    9
    	color: #000;
    
    10
    }
    
    11
    a:hover, a:active, a:visited {
    
    12
    	text-decoration: none;
    
    13
    }
    
    14
    #main {
    
    15
    	width: 780px;
    
    16
        margin: 0 auto;
    
    17
    	margin-top: 50px;
    
    18
    	padding: 10px;
    
    19
        border: 1px solid #CCC;
    
    20
        background-color: #EEE;
    
    21
    }
    
    22
    form fieldset {	border: 0; }
    
    23
    form fieldset p br { clear: left; }
    
    24
    label {
    
    25
    	margin-top: 5px;
    
    26
        display: block;
    
    27
        width: 100px;
    
    28
        padding: 0;
    
    29
        float: left;
    
    30
    }
    
    31
    input {
    
    32
    	font-family: Trebuchet MS;
    
    33
        border: 1px solid #CCC;
    
    34
    	margin-bottom: 5px;
    
    35
        background-color: #FFF;
    
    36
        padding: 2px;
    
    37
    }
    
    38
    input:hover {
    
    39
    	border: 1px solid #222;
    
    40
        background-color: #EEE;
    
    41
    }
    

    Now let's take a look at a few screenshots of what our final project should look like:

    The login form.

    The member area.

    The registration form.

    And Finally...

    And that's it! You now have a members area that you can use on your site. I can see a lot of people shaking their heads and shouting at their monitors that that is no use to them - you're right. But what I hope any beginners to PHP have learned is the basics of how to use a database, and how to use sessions to store information. The vital skills to creating any web application.

    • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
    Advertisement
    Did you find this post useful?
    Want a weekly email summary?
    Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
    Advertisement
    Looking for something to help kick start your next project?
    Envato Market has a range of items for sale to help get you started.