Nathan W. Ho

Silver TheosLogic LogoTheosLogic Productions
penguins
PHP/MySQL Sessions and Web Authentication
By Nathan Ho

Page: 1 2 3 4 5     next page >>

What is a session?!?
A session is the name for a unique visit to a given webserver by a particular end user, and can be tracked by the webserver using a 32-bit hexadecimal string. Note that a unique visit is tracked thus:

  • The first time an end-user visits to your site/server (or after a timeout period has expired).
  • As long as the browser (not browser window) that first visited the site/server has not been closed, AND the timeout period has not expired.

What would we use a session for?
Sessions are most useful when you want to track specific information across multiple pages for a given end user's visit to your site. For instance, if you wanted to have a shopping cart type experience, or to track what a logged in user was doing for a given site - or even to control what parts of a website a given user can visit, as well as control what they can and cannot do on each page.

So how do we use these sessions?
In order to start and carry a session for a given page, we will need to initiate the session first on every page that we want to have the session continue on. We do that by starting off all stand-alone files (as opposed to included files) with the same lines of code:

  • sessions.inc.php - this file contains the new session management functions - this needs to be included in the top of every file, before starting the session. The name of the file doesn't matter, and the only changes that you need to make to it are the 4 MySQL database variables at the top (we'll get to the MySQL tables in a minute).

  • session_start(); - this line starts the session, or continues the existing one
So, at the top of every stand-alone page (except for files that are PHP included), you will need to have these two lines before anything else:

include("sessions.inc.php");
session_start();

The reason that I say that PHP included files don't count is because by trying to start sessions at the top of these files, you in effect try and start sessions twice (which won't work). Also note that you must start your session FIRST on the page - you may not output any text or headers to the browser, or your session will fail (and toss up an error).

Next stop - the MySQL tables!

Page: 1 2 3 4 5     next page >>
 
© Copyright 2001-2009 TheosLogic Productions | Nathan Ho