Sessions
Introduction
- The normal interaction between browsers and web servers is
stateless.
- One way to build a stateful application is to store the
state in the browser and then include these state variables
with each request.
- A second way is to store the state on the server.
A stateful web database application can be built
using a session. This second method will be
our focus using PHP session management techniques.
Session Management Overview
- A session manages the interaction between
a web browser and a web server.
- Components: (1) session variables and (2) a session identifier.
- The session ID is transmitted between the browser and server
with each HTTP request and response. Usually, it is transmitted
as a cookie,
or a named piece of text.
- The session variables are stored on the server.
- Sessions need to have an explicit end or a timeout.
PHP Session Management
- PHP online reference:
CXLIII.
Session Handling Functions
- By default, PHP uses disk-based files to store session variables.
- session_start() - first call
- Generates a new session ID, a 32 bit hexadecimal number.
- Creates an empty file to store session variables.
- Sends a cookie back to the browser with the session ID.
- Note: call session_start() before any HTML output is generated.
- $_SESSION is a global, associative array.
- Unsetting Session Variables: unset($_SESSION["count"]); or
$_SESSION = array();
- session_destroy() - ends session, but does not remove
session cookie from browser
- Sample Code: count.php
Authenticated User Session
Reasons to Use Sessions
- Performance - avoid repeated computations
- Sequence of Interaction - for example, a wizard
- Intermediate Results - for example, remembering the
fields of a form that were entered correctly
- Personalization
Reasons to Avoid Sessions
- Need for a Centralized Store - harder to use multiple servers
- Performance - overhead
- Timeouts - sometimes difficult to know when a session has ended
- Bookmark Restrictions
- Security Issues
Laboratory
Do something interesting and non-trivial that uses sessions.
If you are a Montana State student, demonstrate it during
today's lab period. If you are a University of Leipzig student,
either demonstrate it during today's lab period or e-mail it to
Sebastian (loewe AT uni-leipzig.de) no later than the end of the day.