Transcript More

Web Database Programming
Week 7
Session Management
&
Authentication
Session
• HTTP is stateless
– Each HTTP request is unrelated to one
another
• Many Web applications need to retain
State across HTTP requests
– E.g. Shopping cart
• A Session defines an identifiable
sequence of interactions between a
particular client and a server
Session Components
• Session Identifier (SessionID)
– Uniquely identify a session
• Session variables
– Store information related to a session, I.e.
retain state across HTTP requests
– E.g. content of shopping cart
SessionID
• Is transmitted between client and server with
each HTTP request or response
• Be default, transmitted as cookie (part of the
HTTP header)
– Stored in Web browser
– E.g. “C:\Documents and Settings\Administrator\Local
Settings\Temporary Internet
Files\Cookie:[email protected]/”
• If cookie is disabled
– Put PHPSESSID (32 hex digits) in URL
– E.g.
http://www.xyz.com/demo.php?PHPSESSID
=be20081806199800da22e243ef239391
Session Variables
• Stored in Web server
• Each session has its own set of session
variables
– In PHP, each session has a session file
– E.g. My shopping cart vs. your shopping
cart
• In PHP, access by
$_SESSION[“variableName”]
Session Illustration
PHP Session Management
• session_start()
– If no session exists
• Create a new sessionID and a session file to store
session variables on the server
• Send a cookie to browser with the sessionID
– If session exists (the sessionID in the cookie sent
by browser matches a sessionID on server)
• Session variables in the session file will be loaded
• NOTE: this function must be called before
any HTML output
PHP Session Management
• isset($_SESSION[“variableName”])
– Check if the session variable exists
• unset($_SESSION[“variableName”])
– Remove the session variable
• $_SESSION = arry();
– Remove all session variable
• session_destory();
– Remove the session file from the server
– Note, cookie is still in browser
Authentication
• Check a username, password pair before
grant access
– Web server configuration files
– Using database
• HTTP Authentication
– In HTTP header
• Form-Based Authentication
– Username, password sent as form variables
• May need to use SSL for encryption
Authentication and Session
• Authenticate once
– Form-based
• Use session to retain the authenticated
status
• Until user destroys the session (logout)
or session timeout
Authentication Script
• Include it at the beginning of each PHP
page that needs authentication
PHP File
Loaded
Come from
Login Form?
Yes
Username/Pas
sword Valid?
Yes
Display Page
Content
Authentication Script
Session
Exists?
Yes
Session
Valid?
Yes
Display Login
Form