Managing Sessions and Using Session Variables
HTTP is a “stateless”protocol, it treats each request for a web page
as a unique and independent transaction.
In transaction-based sites, which need to track the activities of each
user. , for example, the common shopping cart used in web stores
requires to keep track of the items each user has short listed for
purchase.
So it is required a method that makes it possible to “maintain
state,” something that allows client connections to be tracked and
connection-specific data to be maintained.
A common solution to the problem is to use sessions to store
information about each client and track its activities. This session data
is preserved for the duration of the visit, and is usually destroyed on
its conclusion.
Client transactions are identified through unique numbers; The
session identifier may be stored on the client in a cookie or it may be
passed from page to page in the URL.
Creating a Session and Registering Session Variables
In PHP, the session_start() function is used to create a client session
and generate a session ID.
Once a session has been created, it becomes possible to register any
number of session variables;
In a PHP script, session variables may be registered as key-value pairs
in the special $_SESSION associative array.
Example : it creates a new client session and registers two session variables:
<?php
// first page
// create a session
session_start();
// register some session variables
$_SESSION['username'] = 'Viji';
CSIJAC Nallur PHP & MySQL
$_SESSION['role'] = 'admin';
?>
On subsequent pages, calls to the session_start() function re-create the
prior session environment by restoring the values of the $_SESSION
associative array. This can be tested by attempting to access the values of
the session variables registered in the previous example:
<?php
// second page
// re-create the previous session
session_start();
// print the value of the session variable
// returns 'Viji'
echo $_SESSION['username'];
?>
On Windows, you typically need to edit the PHP configuration file, php.ini,
and edit the session.save_path variable to reflect your system’s temporary
directory. The default value for this variable is /tmp,a directory that does
not exist on Windows. Using this default value as is will cause your sessions
to fail.
Destroying a Session
To destroy an extant session—for example, on user logout—reset the
$_SESSION array, and then use the session_destroy() function to erase
session data.
<?php
// re-create session
session_start();
// reset session array
$_SESSION = array();
// destroy session
session_destroy();
?>
CSIJAC Nallur PHP & MySQL