<? LESSON 13 ?>
  spacerspacer

Sessions/Login

One of the tasks needed to be accomplished by a web application is keeping track of the current place of the user while they are navigating our website. This may only need to be done on a website where the user logs in, or has access to data that is specific to the user. If we only have generic information, there may be no need to pay attention to who accesses the information, or how many times a user may have been there.

Maintaining State

Keeping track of where the user is, whether they are logged in or not, if they are in the process of making a purchase, or if they are done, etc. is all part of what is called "Maintaining State". Maintaining the state of the user is a particular challenge on a web site. This is due to the fact that unless you take steps, every access by the user look like the first one to a web application. It is this problem that prompts developers to call the internet a "stateless" environment.

The reason why "state" is so hard to maintain on the internet is due to the fact that there is no built in method to determine who in fact is hitting a web page at any one time! Computer use an IP (Internet Protocol) address to identify where to return data on a request for a web page, but many businesses and schools use the same IP address for many users, making this number completely unreliable.

Cookies

Cookies were the original attempt made by the creators of the web to help maintain state for users. Cookies were designed to store data on the machine of the user. This data was designed only to be accessed by the web site that put it there. This allows a website to see if the user had been to the site before, if they were logged in, etc. Cookies have received a very bad rap over the years, but cookies are still a workhorse of state maintenance. You could store a data, say for instance the Customer's unique CustomerID number in a Cookie, and be able to extract that number, match that number to your database, and know which customer with whom you were currently working. Storing user safe data, for instance the CustomerID, can be done in a cookie. The classic mistake would be to store a credit card there. The cookies are viewable by users, and on a multiple user machine, you could thereby allow another person access to someone's credit card.

Sessions

Using another method for storing data about a user, and thus enabling us to maintain state, is to store data in the memory of the server in what is called a "Session" variable. The idea is very similar to storing data in a "Cookie", only instead of using the user's computer to store data, a single cookie is stored on the users machine to identify the user, and the value is paired on the server with a value to identify the user, and store the data in memory on the server. It is important to note that in most technologies that user a Session variable, the default method is to store a cookie on the client machine to identify the user. It is possible to use a "Cookieless" session in PHP, which then stores the session "cookie" in the querystring, and it follows the user from page to page.

Using Session Variables

Using session variables is extremely easy! The only catch in PHP is that you must call a function called "session_start()" on any page on which you wish to check for a session variable. This can lead to some of the warning messages to which PHP is so prone, if you are calling "session_start()" more than once on a page, for instance. Remember to use the "@" symbol before lines of code to supress error messages, or consider removing any "session_start()" calls that may be duplicates!

Below is the code example for extracting data from a row in a database, and inserting it into a session variable:

@session_start(); //must be called first, anytime a session variable is to checked, or created
$sCustomerID = trim($row['CustomerID']); //Grab the Customer's unique ID, from a database
$_SESSION["sCustomerID"] = $sCustomerID; //Enter variable into session variable

To do anything with a session variable you must declare "session_start()" on the page prior to attempting to access the variable. You should also use the "isset()" function to see if the session variable is available to you. If it is not, you may redirect the user back to a login page, for example:

@session_start(); //must be called first, anytime a session variable is to checked, or created
if(!isset($_SESSION['sCustomerID']))
{ //no session var
     myRedirect("login.php?msg=5"); //send user back to login page, as session has timed out
}

The above example sends a user back to the page called "login.php" with the custom function named "myRedirect". Added to the page is the querystring value "msg=5" which is read at the login page, and a message is delivered to the user. Using a single number like "5" to pass a specific message back to a page allows us to send a great number of messages to the user, by only passing a single number.

If an including file starts a session for it's purposes, then we can use @ in front of session_start() to eliminate seeing errors from trying to start the session too many times.

IMPORTANT! If you are using Zephir to host your work (as I assume most of you are) to be able to use sessions this quarter, you have one more hoop to jump through. Please click on the link below and follow all the instructions on the page, or your sessions won't work!

For those of you who are not using Zephir, but want to see the extra suffering students who don't yet have development space must go through, take a look, but bear in mind you don't have to do this normally on a PHP host.

SESSIONS ON ZEPHIR

Session Limitations

The biggest limitation of a session is that it will "time out". This is due to the fact that valuable server memory is taken up every time a new session is created. The data is stored separately for each user, and each session times out on it's own. The default server time is usually 20 minutes. During that time, if the user accesses a session enabled page again, the session is "re-started" and the session is NOT timed out. To remove the session variables, the session is ended with the command "session_destroy()". While this method usually works, it is safest to change the values of the session variables to an empty string first. Doing this allows you to check for the value, and if you had intented to destroy the session on a logout, but only cleared the value back to an empty string, then you still know the user has been "logged out".

session_start(); //start session, even when about to destroy it
$sCustomerID = ""; //change variable to empty string
$_SESSION["sCustomerID"] = $sCustomerID; //Can't set session var to empty string directly
session_destroy(); //removes session variables from memory
myRedirect("login.php?msg=1"); //send user back to login page with message successful logout

Login Pages

We will normally rely on a session variable if we are going to control access to particular pages. We need to allow administrative access to the database data for routine changes to be made, such as price and quantity changes of merchandise. We may also need to allow access to a shopping cart or allow a way for a customer to update his personal data in a database. Each of these methods would likely require a unique set of login pages, each of which would perform one or more of the following tasks. We will start with the administrative login concept, as you will need to access your data during development. Below is a sample login web application, with pages to demonstrate this functionality. Each task is listed in approximate order, with the sample pages listed in bold:

  1. Take data as entered by the user on a form (adminLogin.php), and validate it against a database (adminVal.php)
  2. Create a session variable to hold the data to identify the particular user and redirect the user to a login-protected page (admin.php) upon successful login.
  3. If the user fails the login test, redirect the user back to the login page, with a loaded querystring, which will provide feedback to the user
  4. Use an include file to determine if a user has been authorized to view particular page. Upon failure to be authorized, the user would be redirected to the login page, with an appropriate message (adminOnlyINC.php)
  5. Create a "logout" file, which when clicked, will clear the session variables, destroy the session, and redirect the user back to the login page with an appropriate message (adminLogout.php)
 

This set of example pages can be viewed in action in the link below. Please view the code for more details on the operation of the specific pages involved.   

5/26/2008: The new code is now posted here. Make sure the date on the document you are using is dated May, 2008:                                                                                                                                                                          

adminLogin.php View Code

 

Print this Page Back To Top

© 2002 - 2009 newMANIC INC, All rights reserved