Sessions
HTTP is a stateless protocol; this
means that the webserver does not know (or care) whether two requests comes
from the same user; each request is instead handled without regard to the
context in which it happens. Sessions are used to create a measure of state in
between requests—even when they occur at large time intervals from each other.
Sessions are maintained by passing a
unique session identifier between requests—typically in a cookie, although it
can also be passed in forms and GET query arguments. PHP handles sessions
transparently through a combination of cookies and URL rewriting, when
session.use_trans_sid is turned on in php.ini (it is off by default in PHP5) by
generating a unique session ID and using it track a local data store (by
default, a file in the system’s temporary directory) where session data is saved
at the end of every request.
Sessions are started in one of two
ways. You can either set PHP to start a new session automatically whenever a
request is received by changing the session.auto_start configuration setting in
your php.ini file, or explicitly call session_start() at the beginning of each
script. Both approaches have their advantages and drawbacks. In particular,
when sessions are started automatically, you obviously do not have to include a
call to session_start() in every script. However, the session is started before
your scripts are executed; this denies you the opportunity to load your classes
before your session data is retrieved, and makes storing objects in the session
impossible.
In addition, session_start() must be
called before any output is sent to the browser, because it will try to set a
cookie by sending a response header.
Accessing Session Data
Once the session has been started,
you can access its data in the $_SESSION super-global array:
// Set a session
variable
$_SESSION[’hide_menu’]
= true;
// From here on, we
can access hide_menu in $_SESSION
if ($_SESSION[’hide_menu’])
{
// Hide menu
}
0 Comment to " PHP Sessions &Accessing Session Data "
Post a Comment