Oct
30
Posted on 30-10-2007
Filed Under (Tutorial) by chintan

In PHP session variable is used to store up information about, or modify settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

Session Variables in PHP

While you are working with an application, you open it, do some modify and then you close it. This is much like a Session. Computer knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t continue state.

A PHP session solves this problem by allowing you to store user information on the server for later use. However, session information is temporary and will be removing after the user has left the website. If you need a enduring storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is spread in the URL.

Create a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Message: The session_start() function must appear ahead of the <html> tag:

<?php session_start(); ?>

<html>

<body>

</body>

</html>

The code above will register the user’s session with the server, allow you to start saving user information, and allot a UID for that user’s session.

Store up a Session Variable

The accurate way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php

session_start();

// store session data

$_SESSION['xxx']=1;

?>

<html>

<body>

<?php

//retrieve session data

echo “Page=”. $_SESSION['xxx'];

?>

</body>

</html>

Output:

Page=1

In the example under, we make a simple page counter. The isset() function checks if the “xxx” variable has already been set. If “xxx” has been set, we can addition our counter. If “xxx” doesn’t exist, we create a “xxx” variable, and set it to 1:

<?php

session_start();

if(isset($_SESSION['xxx']))

$_SESSION['xxx']=$_SESSION['xxx']+1;

else

$_SESSION['xxx']=1;

echo “Page=”. $_SESSION['xxx'];

?>

Destroying a Session

If you wish to remove some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php

unset($_SESSION['xxx']);

?>

You can also totally destroy the session by calling the session_destroy() function:

<?php

session_destroy();

?>

message: session_destroy() will reset your session and you will lose all your stored session data.

Share These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • Live
  • StumbleUpon
  • Technorati
  • YahooMyWeb
(0) Comments    Read More   
Post a Comment

You must be logged in to post a comment.