Following up on yesterday’s introduction to PHP Sessions, let’s talk about building a simple login system in PHP. To start, you will need to make sure that pages on your site that are behind the login page will have sessions enabled. This can be done for all of your pages by setting the
session.auto_start or making sure to include
session_start() at the top of your pages. For this walkthrough we’ll be creating a small site that had 4 pages: main index (the home page), login and logout pages and a restricted access page. For the sake of simplicity we’ll be using a hardcoded username and plaintext password. For obvious reasons we don’t recommend doing so and at the very least you should be encrypting the password.
To start off, let’s put together our home page
Nothing fancy, we start the session and check to see if the username is set in the session. If it is, give some secret options, if not, present the user with the opportunity to login. Speaking of logging in, on to the login page,
A bit more going on in this one, out of the gate we start our session and then check to see if the user is already logged in. If they are logged in, we send them back to the home page as there’s no reason for them to be logging in again. After that, we check to see if the login credentials have been supplied and check if they are valid. If they are not, we display an error, if correct send them back to the home page as they are now properly authenticated. Lastly we display the login form which is set up to post back to itself, that’s why all of the login logic exists in the same file. You could very well abstract out the login logic to it’s own file, perhaps
login/process.php or something similar. As mentioned before, the username and password are hardcoded and it is not recommended for use outside of this example. The check if the information is correct could be swapped out to check a database or other datastore as well as hashing the password as you should never store plaintext passwords.
Now that you have out page to log the user in, let’s set up our “secret” page named
secret.php. The page is very similar to our main index with the difference that unauthenticated users will be will served an HTTP Error Code (401 Unauthorized) instead of a message to log in.
Now we have a page that’s completely locked out to unauthorized users. Last but not least, we need to write a log out script that will destroy the session. This file will be named
logout.php and will be our shortest script because it doesn’t have any markup. To keep things simple we won’t check if the user is logged in or not, just destroy the session and redirect:
That’s it, you now have a simple site that has a login system! Tomorrow’s post will be a continuation of PHP Sessions by delving into some advanced configuration options.