PHP – Sessions

by Hiroshi on June 23, 2008

in isset, Sessions

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. A visitor accessing your web site is assigned a unique id, the session id. This is either stored in a cookie on the user side or is propagated in the URL or can be stored in database. A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. This makes it quite a problem for tasks like a shopping cart, which requires data (the user’s selected product) to be remembered from one page to the next.

Sometimes we store id, name and other information about user in PHP Sessions. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.

Sessions work by creating a unique identification (UID) number for each visitor and storing variables based on this ID. This helps to prevent two users’ data from getting confused with one another when visiting the same web page.

We can start, call or retrieve and use or destroy session or session data.

Starting a PHP Session

Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.

Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session.

<?php
session_start();
// start up your PHP session!
// this code must be at the top of web page.
?>

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

Storing A Session Variable

<?php
session_start();
$_SESSION['downloads'] = 1; // store session data
echo "Downloads = ". $_SESSION['donloads']; //retrieve data
?>

Using PHP issetFunction

<?php
session_start();
if(isset($_SESSION['views']))
    $_SESSION['views'] = $_SESSION['views']+ 1;
else
    $_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
?>

Destroying Sessions

<?php
session_start();
session_destroy();
// By this all the session data will be erased and session will be reset, free and empty.
?>

OR

<?php
session_start();
session_destroy();
$_SESSION=array();
?>

Selectively Destroying Session Data

<?php
session_start();
unset($_SESSION['downloads']);
unset($_SESSION['userName']);
// session_destroy();
// $_SESSION=array();
// By this all the session data will not be lost. Just downloads and userName will be destroyed from session and if other data is ther, it will stay there.
?>

Related Posts

Previous post:

Next post: