Home / PHP/MySQL Tutorials / Archive by category 'PHP sessions'

PHP sessions

Decode string back into variables in PHP

<?php
$fp = @fopen("save_items.txt", "r")
             or die("Cannot open save_items.txt");
$data = fread($fp, filesize ($fp));
@fclose ($fp)
     or die ("Cannot close save_items.txt");
 
session_decode($data);
foreach ($items as $item) {
    print "$item\n<br>\n";
}
?>

Encode session data to a string using PHP

Developers may want to save all the current session variables in string format and extract them back into variables at a later point. This can be achieved using session_encode and session_decode functions.

<?php
session_register("my_items");
$my_items = array("one", "two");
 
$string_items = session_encode();
$fp = @fopen ("save_items.txt", "w")
              or die ("Cannot open save_items.txt");
@fwrite ($fp, $string_items);
@fclose ($fp)
    or die ("Cannot close save_items.txt");
print "Items Written";
?>

Save objects in session using PHP

It is easy to store an object in a session in PHP. We can do it using session_register(). We must always include the class definition in every place you use the object.

person_class.inc:

<?php
//
// File:  person_class.inc
//   Contains the class definition necessary to let an object be a session
//   variable.
//
class Person
{
    var $name;
    var $email;
 
    //
    // A simple function to illustrate the point
    //
    function clean_name ()
    {
        $name = preg_replace("/h(.)+/i", "\\1", $this->name);
        return substr($name, 0, 15);
    }
}
?>

main.php:

<?php
//
//  File:  main.php
//    Here is where we save and retrieve the object
//
include_once 'person_class.inc';
 
session_register('someperson');
 
if (!$someperson) {
    $someperson = new Foo;
    $someperson->name = "Item Raja";
    $someperson->email = "itemraja@php.net";
    $someperson->clean_name();
}
?>
<a href="somePage.php">Click Here</a>

somPage.php

<?php
//
//  File: somePage.php
//    Print out the name without initializing the
//    class and setting the variables
//
include_once 'person_class.inc';
 
session_register('foobar');
print $foobar->name;
?>

Clear all variables in current session in PHP

We can use the session_destroy() function for deleting all the session variables in the current session. The session_destroy() function will delete the session data from the session store. It will not delete session variables’ contents. The session_unset() function can be used to go through all session variables and remove them from the symbol table.

<?php
session_start();
 
session_register("my_var1");
session_register("my_var2");
 
$my_var1     = "w3mentor";
$my_var2  = "w3schools";
 
session_destroy();
print $my_var1;
?>

Remove a session variable in PHP

We can use PHP’s session_unregister() function instead of unset() to remove the variable from the session. The session_unregister() function removes the specified variable from the session registry, so that when the session is saved, it will not contain the newly unregistered variable. This function does not delete the variable’s contents.

<?php
session_register('my_var');
if (session_is_registered('my_var')) {
    session_unregister('my_var')
        or die('Could not unregister my_var');
}
?>

Change session name in PHP from PHPSESSID

The session_name() function can be used to change the name of the session cookie.The new session name must be alphanumeric and the session_name() function must be called before the session_start() function or session_register() function.

<?php
$old_session = session_name('SomeSiteSession');
//
// when called with no parameters session_name
// simply returns the current session name
//
$new_session = session_name();
 
// register a new session variable
session_register('my_variable');
 
print "The old session name was: $old_session, ";
print "the new session name is $new_session";
?>

Save PHP sessions to a database

We can use the session_set_save_handler() function to register functions that are working with the database. session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

Example:

<?php
//
// 'sessions' table schema
// create table sessions (
//   session_id char(32) not null,
//   session_data text not null,
//   session_expiration int(11) unsigned not null,
//   primary key (session_id));
//
 
include_once 'DB.php';
 
// Global Variables
$dbh = NULL;
 
function on_session_start ($save_path, $session_name) {
    global $dbh;
    $dbh = DB::connect('mysql://user:secret@localhost/SITE_SESSIONS',
                       true);
 
    if (DB::isError($dbh)) {
        die(sprintf('Error [%d]: %s',
                    $dbh->getCode(), $dbh->getMessage()));
    }
}
 
function on_session_end ()
{
   // Nothing needs to be done in this function
   // since we used persistent connection.
}
 
function on_session_read ($key)
{
    global $dbh;
 
    $stmt = "select session_data from sessions";
    $stmt .= " where session_id = '$key'";
    $stmt .= " and session_expiration > now()";
 
    $sth = $dbh->query($sth);
    $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
    return $row['session_data'];
}
 
function on_session_write ($key, $val)
{
    global $dbh;
 
    $val = addslashes($val);
 
    $insert_stmt = "insert into sessions values('$key', '$val', now() + 3600)";
    $update_stmt = "update sessions set session_data = '$val', ";
    $update_stmt .= "session_expiration = now() + 3600 ";
    $update_stmt .= "where session_id = '$key'";
 
    // First we try to insert, if that doesn't succeed, it means
    // session is already in the table and we try to update
    if (DB::isError($dbh->query($insert_stmt)))
        $dbh->query($update_stmt);
}
 
function on_session_destroy ($key)
{
    global $dbh;
 
   $stmt = "delete from sessions where session_id = '$key'";
   $dbh->query($stmt);
}
 
function on_session_gc ($max_lifetime)
{
    global $dbh;
 
    // In this example, we don't use $max_lifetime parameter
    // We simply delete all sessions that have expired
    $stmt = "delete from sessions where session_expiration < now()";
    $dbh->query($stmt);
}
 
session_start ();
 
// Register the $counter variable as part
// of the session
session_register ("counter");
 
// Set the save handlers
session_set_save_handler ("on_session_start",   "on_session_end",
                          "on_session_read",    "on_session_write",
                          "on_session_destroy", "on_session_gc");
 
// Let's see what it does
$counter++;
print $counter;
session_destroy();
?>

Retrieve the Session ID of the current session using PHP

There are two ways to get the session id for a visitor. A call to the session_id() function will return the session ID value. Another way is to use the built-in constant SID. SID contains a string of session ID name and value.

Example code to retrieve the session ID:

<?php
  session_start();
  print("<html><b>");
 
  $sid = session_id();
  print("Session ID returned by session_id(): ".$sid."\n");
  $sid = SID;
  print("Session ID returned by SID: ".$sid."\n");
 
  $mysite = $_SESSION["mysite"];
  print("Value of mysite has been retrieved: ".$mysite."\n");
  print("</b></html>\n");
?>

Output:
Session ID returned by session_id(): rfnq17675gtrfejbtc46n0vi97
Session ID returned by SID: PHPSESSID= rfnq17675gtrfejbtc46n0vi97
Value of mysite has been retrieved: W3M

The session ID created by the PHP engine is 26 characters long with alphanumeric characters only.


Session IDs in PHP

A session ID is an identification string of a session. The PHP engine maintains multiple sessions concurrently one per visitor to the site. Session IDs are created and maintained by the PHP engine to identify sessions.
When a visitor comes to your Web site requesting the first PHP page for the first time, the PHP engine will create a new session and assign a unique session ID to this new session. The first PHP page can set some values to the session. When the same visitor clicks a hyper link requesting the second PHP page, the PHP engine will use the same session ID to find the same session created for the first page and give it to the second page. No new session will be created for the second page.


Retrieve values from the current session in PHP

We can retrieve the values stored in a session by using the pre-defined associative array called $_SESSION. The following PHP script shows you how to retrieve values from the session:

<?php
  session_start();
  print("<html><b>");
 $_SESSION['sitename'] = "W3M';
  $sitename = $_SESSION["sitename"];
  print("Value of sitename has been retrieved: ".$sitename."\n");
 
   print("</b></html>\n");
?>

Output:
Value of sitename has been retrieved: W3M


Save information in the current session in PHP

The pre-defined associative array called $_SESSION can be used to store session specific information. The following PHP script shows you how to save values to the session:

Example code:

<?php
  session_start();
  print("<html><b>");
 
  $_SESSION["sitename"] = "W3M";
  print("A value saved in the session named as sitename.\n");
 
  $_SESSION["MyChoice"] = "red";
  print("A value saved in the session named as MyChoice.\n");
  echo $_SESSION['sitename']."\n";
  echo $_SESSION['MyChoice]."\n";
  print("</b></html>\n");
?>

Output:
A value saved in the session named as MyLogin.
A value saved in the session named as MyColor.
W3M
red


How to enable session support in PHP

The session support can be turned on automatically at the site level, or manually in each PHP page script:

  • Turning on session support automatically at the site level can be done by setting session.auto_start = 1 in php.ini.
  • Turning on session support manually in each page script can be done by calling session_start() funtion.

Sessions in PHP : Part 4 – Cleaning and destroying PHP session

The unset() function is used to unset or free a session variable that has been set. A session can be completely destroyed by using the session_destroy() function.

Example code:

1
2
3
<?php
unset($_SESSION['views']);
?>

All the stored data of the session will be deleted on calling the session_destroy() function.

Example code:

1
2
3
4
<?php
Session_start();
session_destroy();
?>

Sessions in PHP : Part 3 – Storing and retrieving session variables

The $_SESSION associative array is used to store and retrieve session variables. This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
<?php
session_start();
//storing session variable
$_SESSION['views']=1;
?>
 
<html>
<body>
 
<?php
//retrieving session variable
echo "Pageviews=". $_SESSION['views'];
?>
 
</body>
</html>

Output:

Pageviews=1

In the above example, the session variable views is used to store the number of times a page has been viewed.


Sessions in PHP : Part 2 – Starting a session

Before storing the information for a user session, the session should be started using the session_start() function. This function should appear before the tag.

Example code:

1
2
3
4
5
6
7
8
9
<?php session_start(); ?>
 
<html>
<body>
 
//rest of the code
 
</body>
</html>

The above code will register the user’s session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user’s session.


Sessions in PHP : Part 1 – Introduction

A session refers to the time spent by a user at a particular website with a unique IP address before moving to a different website or closing the website. PHP provides support for web programs to remember certain data across various user sessions by storing the data of a session on the server for later use.

A session variable is used to store information on the server. Sessions work by creating a unique identification (UID) number for each visitor and storing variables based on this UID.