Intro
At the end of my last post, we had just finished authenticating that a user registering for your site was in fact, a human. Now we’re gonna go a step further and discuss registering them, and creating a simple login system that uses form-based authentication, or more specifically, a form-based authentication system that uses html and http.
Registering
Setup
Registering a user for your site means that you gather various pieces of information about your user, and store it in your system, for later access. For the most simplest of registrations, you’ll need at least a username (handle), and a password. Optional information that you could want would be anything from an email address, to a location in the world (city, state, country), to a specification of gender and ethnicity. It’s up to you and how you build your community, and what’s important to keep track of. So based on that, you’ll have a form based off of the one below:
<form method="post" action="register.php"> <input type="text" name="username" /> <input type="password" name="password /> <!-- Any various more information you want here --> <input type="submit" value="Register!" /> </form>
You’ll notice that we’re sending things server side, using the “POST” method defined in the http. This is generally the proper way as defined in the protocol, as POSTing something is for saving data on the server, while GETing something is for retrieving data. This is something we’re going to have to take note of, while writing our registration script.
Saving
In PHP, if you run var_dump on $_POST after a form submission, you’ll see that it’s an associative array, that looks something like this:
array(2) { ["username"]=> string(5) "fubar" ["password"]=> string(6) "abc123" }
So to retrieve those values, we simply do this:
< ?php $username = $_POST['username']; $password = $_POST['password']; ?>
From there, we create a new user in the database, by inserting all the data about them that we’ve gathered.
< ?php mysql_connect( "host", "username", "password" ); mysql_select_db( "database" ); mysql_query( "INSERT INTO `users` VALUES( NULL, '$username', '$password' )" ); ?>
Side Note: The “NULL” in that insert statement is for the user_id in the database, i.e. a unique identifier for each user. In MySQL that’d be set up as an auto-increment primary key.
Logging In
Setup
After the registration form, logging a user in is quite simple. It takes a form, like the one above,
<form method="post" action="login.php"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="Login" /> </form>
Contrary to the registration form, however, we only need the username and the password, not everything else, in order to log in.
Logging in
The act of logging in is simple. You get the password from the form, and compare it to the one in the database, that is linked to the username.
< ?php $username = $_POST['username']; $password = $_POST['password']; mysql_connect( "host", "user", "password" ); mysql_select_db( "database" ); $query = mysql_query( "SELECT * FROM `users` WHERE `username` = '$username'" ); $row = mysql_fetch_assoc( $query ); if( $row['password'] == $password ) setcookie( "<sitename>_login", $username ); ?>
Staying in
Cookies
This is one of two ways, and is the easier and cleaner way to take care of this. When a user logs in, you set a cookie on his browser, preferably something with a unique name. In my example, I use “
This works in the same way a login works, only without the influence of a user. You get the cookie value, check to see if it’s correct, (in this case, if the username value given exists in the database), and then base your user’s experience off of that.
Sessions
The is the second way, and a teensy bit harder to deal with, especially if you don’t have files to handle boiler-plate stuff like this for you. The way to initialize a session is by calling session_start at the beginning of EVERY SCRIPT that displays different output depending on who’s viewing it.
< ?php session_start(); ?>
That function call HAS to come before any output at all ever. Period. Then, instead of setting a cookie, you set a $_SESSION variable.
< ?php $_SESSION['username'] = $username; ?>
Then, for every link that the user clicks through, to keep the session alive you need to add what’s called the session id to the end of it. What happens is that when session_start is called, it checks the query string of the page for “PHPSESSID”. If it exists, it uses that ID to continue the session. So, to make sure that the session id is stapled onto each link we output, we add the SID constant to the end of each url:
<a href="<?php echo "random_file.php?" . SID ?>">Link</a>
Getting Out
Cookies
Most cookies last for as long as the browser is open, and sometimes that can last a while. Others, depending on the parameters given to setcookie can last longer than the browser session; days, months even. Sometimes a year but you don’t see that often. So, to counteract this, you set the cookie’s time limit to sometime in the past.
< ?php setcookie( "name", "", time() - 3600 ); ?>
Setting it to an empty string is just a precaution we can take as well to make sure that it doesn’t exist.
Sessions
Sessions are a little bit trickier to handle as there’s TWO things that need to be reset, yet when I say “a little bit”, I seriously mean “a little bit”.
< ?php session_start(); $_SESSION = array( ); session_destroy(); ?>
First off, we have to start up the session otherwise there’d be nothing to destroy. We then set the super-global $_SESSION to an empty array, effectively getting rid of whatever value we had in there. Last but not least, we call session_destroy to kill the session for us.
Summary
This post has gone over three different things, all relatively simple. User registration, user login, and keeping the user logged in. They shouldn’t be that hard of a set of concepts to grasp, as you have to do this for nearly every website you visit (facebook, myspace, etc). The whole point of this post was to set down a summary of what needs to happen to allow users to use your site at a different level than lurkers. Again, if you your site is to just showcase things that you’ve made (like an image gallery), then there’s no need to have this.
Also of note, is that the methods described here are far and beyond not-secure. If you’re site is popular enough, and user security has to be on the call list, then wait for my next post. Part 2 will combine everything we learned here with various secure ways to authenticate a user that browsers use when given a page that requires a username/password to view.
