Php Sessions


by Php Ninza on July 14, 2009

The problem with the HTML is that it cannot retain the values of variables from one page to the next page. All the data values of the previous page are forgotten when the next page is reloaded. To solve this problem, PHP is used. PHP allows transferring data values from one page to the next page using Forms and Hyperlinks. This is easier if the users are few but chances of confusion of data values filled by two or more different users increase when they are visiting the same webpage at the same time. To solve this problem, session handling is done in PHP.

A session created in PHP helps to retain the data values of variables from one page to the next page. Though this information is temporary and is destroyed when the session is destroyed but it can be used on all pages where session continues. All sessions provide a different unique ID to the users and this helps to avoid any mismatching of data. Session should be started before storing data in sessions. The important point to remember is that the code to start the session should be placed in the first line of any webpage otherwise if some other code is placed before session starting code then the session function will not work correctly. Code to start the session is as:

<?php

session_start();

?>

And after the above lines of code remaining code can be placed below it as shown below.

<html><head></head>

<body>User Session is started.</body>

</html>

“Session_start()” function registers the session for the user by assigning a unique ID on the server and allow to save information for that session. To save the information in a registered session, associative array of $_SESSION is used. Few lines of code below will show how to perform this operation.

<?php

session_start();

$_SESSION[‘visits’]=1;

echo “Number of Visits to this page = ”. $_SESSION[‘visits’];

?>

The output of this code will be as below:

Number of Visits to this page = 1

Every time this script is executed the result is increased by one. The main use of session handling comes in while the user is surfing the pages within its own User Account. Session variables help to retain the values of username and password with any other required information. After the user has finished his or her work in User Account area, then the values of session variables are needed to destroy. Following four lines of code will allow destroying the session variables.

<?php

session_start();

session_destroy();

?>

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

{ 1 comment… read it below or Shout @ me! }

tek_news August 10, 2009 at 5:58 am

Reddit/p: Php Sessions http://bit.ly/cLsRr

This comment was originally posted on Twitter

Leave a Comment

Previous post:

Next post: