Handling sessions with PHP

Samantha Mathara Arachchi,
B.Sc,Pg.Dip(Com.Tech.),Pg.Dip.(IM),M.Sc.(IM),MCS(SL) MACM,MIEEE

e-mail:(ssp@ucsc.cmb.ac.lk)
Advanced Digital Media Technology Center-University of Colombo School of Computing

Managing the "Memory" of the Browser
•Web pages are normally completely without memory. •Each time a person visits a page, the web server happily sends the page with no idea if the visitor is viewing the page for the first time or the hundredth. Often times this is not a problem. •Sometimes, however, it is a big problem, such as when you want to identify a user, in order to interact with that person in various ways, even if he/she moves between different webpages. •One method is to use cookies, which are totally dependent on the settings of the client’s web browser.

What is a session ?
•A session is a series of related interactions between a single client & a web server, taking place over an extended period of time. •It is a method of making Data persist, even when you exit one page & go to another.

Session Variables
•How do we make the Browser remember a certain unit of data while we navigate from page to page? Simply, assign that data to a “session variable”, using the following format - $_SESSION[“ << some unique name >> ”]. eg. :$_SESSION[“stu_name”] = “Mr. ABC”, $_SESSION[“stu_id”] = 8880123 •Here, stu_name and stu_id uniquely identify a variable. •Another method is, to use the predefined function session_register(“ “)

Starting or Resuming Sessions
•A function called session_start() is used to start/create or resume a session in a particular webpage, based on the session id based on a GET or POST variable or a cookie. •This allows you to access the session variables input through a previous webpage. This is called initializing sessions. •Two important points that have to be remembered about this function are, - Every sessions enabled page requires it. You must put it before any HTML or PHP output (including blank lines or spaces).

Stopping Sessions
Often times, you will need to destroy a session completely. This is a simple two step process: session_unset(); session_destroy();

Sample Codes
<?php // You don't need session_start() // in the first HTML form page. ?> <html> <body> <form method=post action=page2.php> <input type=text name=Info> <input type=submit> </form> </body> </html> <?php session_start(); $_SESSION["data"]=$_POST["Info"]; ?> <?php session_start(); ?>

<?php session_start(); echo $_SESSION["data"]; ?>