PHP Tutorial - MySQL User System

The system you are about to learn to make can be downloaded -here- .

This tutorial is a fair bit more complex than my previous tutorials, but its widely requested, if anything goes over your head, try my other tutorials, as they explain the individual aspects (insertion, displaying mysql data etc.) so here goes - I will first try to give an overview of the system, I have set it up into 5 separate files, as shown below:



This means that we can effectively separate the style, html, php functions and the main file itself - this makes it a *lot* easier to see what is going on.

The SQL

First I will deal with the mysql, to create the table, copy this into either the command line, or the sql section of phpmyadmin (or whatever you use)

CREATE TABLE userdb ( id int(11) NOT NULL auto_increment, uname varchar(20) NOT NULL default ”, upass varchar(50) NOT NULL default ”, uemail varchar(100) NOT NULL default ”, PRIMARY KEY (id) ) TYPE=MyISAM;

This will create a simple table, with username, password, email and a unique user id, which is also the primary key.

The HTML

We are going to store all the HTML in a separate file, named forms.php - we store the separate forms in separate variables, the first one is called $options_html, and contains 4 forms, one to register, one to login, one to logout, and one to view the registered members. Now i assume you know how to assign a value to a variable, as shown below:

$options_html = ‘<table width=’500′ border=’0′>’ ;

But what you might not know, is that you can add to a string variable, by using the dot . character, as shown below:

$options_html .= ‘<tr><td colspan=’4′ align=’center’><hr width=’400′ class=’hr’></td></tr>’ ;

Now i also assume that you know basic HTML, so to save people having to read 20 pages, here is a link to the $options_html source . Simply copy that into a php document called forms.php, and we’ll get on to the next stage. The only complication is the action of the form, which is set to $_SERVER[’PHP_SELF’] - this makes the action of the form, the document itself (i.e. it reloads the current page) - you can then (as you will see) perform operations based on which forms are set.

The Registration Form

We want people to be able to enter their desired username, password and email address, the ID will be assigned automatically, as the ID field is auto-incremented each time you add a new record to the database. To achieve this, we make a form with four input fields, a desired username, two password fields (so we can check that they have entered the password they think they have) and an email address. The html for this is HERE .

The Login Form

The login form html is here for you to download, as with all the other forms, it simply reloads the current document with the form variables set, we will manipulate these variables on the next page.

Note

I am aware the HTML was somewhat rushed through, if anybody has any problems please ask in the forum and I will explain further, the full html source is here, I called this forms.php.

—————–

The Main Page

Planning the page is important, and pseudo code is my favored method of getting a gist of what needs doing, here is a plan of the main page:

———————————————————————————————-
start the session
include the required files
include the stylesheet

if the ‘login’ button has been pressed, display the login form

if the ‘logout’ button has been pressed, destroy the session, and unset the variables

if the ‘register’ button has been pressed, display the registration form

if the registration form has been set, check that the passwords match, and that all fields have been filled in, if they are, add their details to the database and tell them that they have registered.

if the login form has been set, set the session variable ‘$logged_in’ to be true, if the username and password match, set the session variable ‘$logged_in’ to be TRUE, if not tell them that their login was unsuccessful

show the $options_html variable from forms.php
———————————————————————————————-

*Very* quick overview of sessions

OK, sessions are similar to cookies, in that they store data about visitors, (such as whether they are logged in or not), this data ca be carried from page to page, by storing them in an array, called $_SESSIONS[”] - where the variable name is stored in the quotation marks. You can only access these variables after using the session_start() function (no guessing what that does), after that you access the variables simply by using $_SESSION[’variablename’]. There are a lot of tutorials on the internet concerning sessions, however not many are up-to-date, I may write a more in-depth one at a later date, however until then I very much recommend the sitepoint forum for help.

Into PHP

Now lets convert that pseudo code into real PHP code, here goes.. You will undoubtedly not recognize some functions that I use, that is because they are user-defined, and will be covered on page three.

// Start the session, and include the files, and echo the stylesheet
session_start ();
include ( ‘functions.php‘ );
include ( ‘forms.php‘ );
echo ( ‘<title>USER OPTIONS</title><link rel=’stylesheet’ type=’text/css’ href=’userstyle.css’>’ );

// If the login button is set, display the login form
if ( isset ( $_GET [ ‘login’ ]))
{
echo ( $loginform_htm );
}

// If the logout button is set, log the user out
if ( isset ( $_GET [ ‘logout’ ]))
{
unset ( $_SESSION [ ‘logged_in’ ]);
session_destroy ();
echo ( ‘You are being logged out, please wait..’ );
echo ( ‘<META HTTP-EQUIV=’refresh’ content=’1; url=’.$_SERVER[’PHP_SELF’].’?'>‘ );
}

// If the register button is set, let the user register if the form validates

if ( isset ( $_GET [ ‘initial’ ]))
{

// Check to make sure it is valid

if ( userval ( $_GET [ ‘uname’ ], $_GET [ ‘upass’ ], $_GET [ ‘upass02′ ], $_GET [ ‘uemail’ ]))
{

// Add their details to the database if they are valid

mysql_connect ($host,$user,$pass) or die ( mysql_error ());
mysql_select_db ($db) or die ( mysql_error ());
$add_user = ‘insert into $tablename values(”,’$_GET[uname]’,md5(’$_GET[upass]’),’$_GET[uemail]’)‘ ;
mysql_query ($add_user) or die ( mysql_error ());
echo ( ‘<br><span class=’text’>You have been added to our user list.</span>‘ );
unset ($uname,$upass,$uemail);
}
else
{
echo ( ‘The form did not validate, please try again.‘ );
}
}

// Add their details to the database if they are valid
if ( isset ( $_GET [ ‘login_form’ ]))
{
if ( login_check ( $_GET [ ‘login_uname’ ], $_GET [ ‘login_upass’ ]))
{
echo ( ‘<br><span class=’text’>Well done - you have logged in successfully</span>’ );
$_SESSION [ ‘logged_in’ ] = true ;
}
else
{
echo ( ‘<br><span class=’text’>Sorry, your login was unsuccessful - <a href=’.$_SERVER[’PHP_SELF’].’?login=set>try again?</a></span>‘ );
}
}

// Show the forms with the login/logout/register buttons on them
echo ( $options_html );

An explanation?

Ok that’s probably a bit of a handful to take in all at once, but if you look at it in sections, where the comments are, they explain what everything does, but here is a quick overview of the functions used…

isset () - this checks to see if a variable is set, in this case, a form variable - when the submit button is pressed it ’sets’ the hidden variable in the form, for example the options_html variable contains this line: $options_html .= ‘< input type=’hidden’ name=’logout’ value=’set’>’ ; — the variable is called ‘logout’ and if it is set, the session is destroyed, and the user is no longer logged in (line 14, above).

Global Variables - $_GET , $_POST , $_SESSION , $_SERVER etc. - these, from php version 4, must be used in place of the simple variable names that you might be used to, if a form has method ‘post’ then to access a variable from inside it, you would use $_POST [’variablename’], $_SESSION is used to access session variables, and $_SERVER to access server variables, such as PHP_SELF.

unset () - this un-sets a variable, so it cannot be used unless it is re-assigned a new value

The user functions i talked about are login_check() and userval(), you can see what they do next …

OK then, the functions

Right, the infamous functions that I’ve been talking about - first of all, I assume that you know how functions work (i.e. you put an argument and get a result returned, I’ve made it even easier here, in that the function only returns TRUE or FALSE).

User Validation

First of all, we need to have a function to validate the user details, which i called userval(), it takes 4 arguments - uname, upass, upass02 and uemail - so we can validate their username, password and email address from the registration form -the function is far too long to post all on this page (well, without a ridiculous amount of scrolling, so here is a link to it . The function is all nicely commented, and all you will need to alter is the database settings at the very top ($host, $user etc.).
This function checks:

  • That the identity is not already in use
  • That the username is not too long
  • That the username and password are entered
  • That the password is valid
  • That the email address is valid

It returns true if the criteria are met, and false if they are not.

The Login Function

The login function This function is rather shorter, and i will explain it step-by-step. First it takes the username and password submitted by the login form and assigns the database settings - change these to suit - then it connects to the database, selects the appropriate database, and this is the crux of it. It selects all the records where both the username is the username submitted, AND the password is the password submitted (and as we checked that the username couldn’t be duplicated, there will either be one result (they can login) or no result (their username/password isn’t there). We use the mysql_num_rows () function, which counts the number of rows in a result of a query to see whether they can log in, if they can we set the function to return TRUE, if not it returns FALSE.

function login_check($login_uname,$login_upass)
{
$host = ‘localhost‘ ;
$user = ‘huscy‘ ;
$pass = ” ;
$db = ‘ex‘ ;
$tablename = ‘userdb‘ ;

// Check to make sure theyre set, and valid
if ($login_uname && $login_upass)
{
// Check to make sure they are users, and have correct password

mysql_connect ($host,$user,$pass) or die ( mysql_error ());
mysql_select_db ($db) or die ( mysql_error ());
$check_user_query = ‘select uname,upass from $tablename where uname = ‘$login_uname’ and upass = md5(’$login_upass’) ‘ ;
$check_user = mysql_query ($check_user_query) or die ( mysql_error ());
if ( mysql_num_rows ($check_user) != 0)
{
return TRUE;
}
else
{
return FALSE ;
}
}
else
{
echo ( ‘<br><span class=’text’>You must enter a username AND password</span>’ );
}
}

Summary so far

OK, so far we’ve covered the functions, the html, and the main page, the two remaining pages are pretty much optional - first the test page, all this does is, based on whether the user is logged in or not, display a message, as shown..

// Start the session
session_start ();

// If they are logged in, tell them so, if not - tell them they’re not, and allow them to login via a link

if (isset($ _SESSION [ ‘logged_in’ ]))
{
echo ( ‘You are logged in - <a href=phptut_usersystemexample.php>back</a>’ );
}
else
{
echo ( ‘You are not logged in - <a href=phptut_usersystemexample.php?login=set>log in</a>’ );
}

The Stylesheet

Very, very simple yes - good now on to the (also optional) stylesheet - I use this because I absolutely despise times new roman with a passion, and the entire stylesheet is shown below:

body {
font-family: Arial, Verdana, Helvetica,
sans-serif;
font-size: 10pt;
}

a:link { text-decoration: none; color: #990000; }
a:visited { text-decoration: none; color: #990000; }

Conclusion

And save that as userstyle.css (or whatever you want, just remember to change it where you link it as well). and there you go, a nice, transferable mysql driven user system, all you need to do on any subsequent pages is that which is on the test page, except where it says ‘you are logged in’, put the content that you want users to see, and a message telling unregistered users to go register. I have also included a ‘view all users’ button in my example - try my displaying mysql results tutorial to see how to do this.

Rating: