Setting / Getting Sessions Values in PHP

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.

1. IDU is stored on server (i.e. server-side)
2. Safer (because of 1)
3. Expiration can not be set, session variables will be expired when users close the browser. (nowadays it is stored for 24 minutes as default in php)

1. IDU is stored on web-browser (i.e. client-side)
2. Not very safe, since hackers can reach and get your information (because of 1)
3. Expiration can be set (see setcookies() for more information)

Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.

Cookies is preferred when you need to store long-term information/values, such as user’s account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can’t think of many examples for cookies since it isn’t adopted in most of the situations.

1. A PHP session is started with the session_start () function. This function has to be written above the html tag in your program:

<?php session_start(); ?>

2. Sessions can be accessed using


3. Storing single session variable:

$_SESSION['item_id'] = $post_id;

4. PHP Session Array:
Example A:

$userinfo = array();
$userinfo['username'] = 'currentusername';
$userinfo['isloggedin'] = false;
$userinfo['UID'] = 1;
$_SESSION['userinfo'] = $userinfo;

Example B:
$_SESSION[‘userinfo’][‘username’] = ‘currentusername’;
$_SESSION[‘userinfo’][‘isloggedin’] = false;
$_SESSION[‘userinfo’][‘UID’] = 1;

5. Sessions are closed using:

<?php session_destroy(); ?>

Do you need help with a project? or have a new project in mind that you need help with?

Contact Me