Php sessions: advanced session files managing practice

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- Filament.io 0 Flares ×

Sometimes we need to manage PHP sessions by ourselves, avoiding preprocessor to default. This can be useful for having high control about session data. So I wrote some lines of code which can do the magic:

Php Sessions
Php Sessions
// ...
// calculating 7 days
$cookieExpireTime = 60*60*24*7;
// setting up the expiring date of the session
session_set_cookie_params($cookieExpireTime,'/','.mydomain.com');
// setting up session max lifetime:
// it can be different from cookie lifetime
$Lifetime = $cookieExpireTime;

// some code for choosing the
// correct directory separator by OS
$Separator = (strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN")) ? "\\" : "/";
// set up the name of our
// session data directory (SessionData):
$DirectoryPath = dirname(__FILE__) . "{$Separator}SessionData";
is_dir($DirectoryPath) or mkdir($DirectoryPath, 0755);

// change session managing from url to cookies
if (ini_get("session.use_trans_sid")==true){
    ini_set("url_rewriter.tags","");
    ini_set("session.use_trans_sid",false);
}

// setting up php session garbage collection parameters
ini_set("session.gc_maxlifetime",$Lifetime);
ini_set("session.gc_probability", "1");
ini_set("session.gc_divisor", "2");
ini_set("session.cookie_lifetime", "0");

// finally change session data files path
ini_set("session.save_path", $DirectoryPath);

// using PHPSESSID default php cookie for sessions
if (isset($_COOKIE["PHPSESSID"]))
    {
        session_id($_COOKIE["PHPSESSID"]);
    }

// session start!
session_start();
// ...

The above code is self explaining and allows to keep all session data files in a directory that we can manage instead the default Php directory. Also I added a simple expire managing for all the sessions.

This trick is simpler than storing sessions in DB and lets you see and edit all the data inside user’s sessions that shows as the following example:

File “sess_XXXXXXXXXXXXXXXXXX”:

var1|i:0;logged|i:1;username|s:5:"xxxxx";idlogin|s:1:"3";name|s:5:"xxxxx";iduser|s:1:"3";userlevel|s:2:"10";var2|s:0:"";

As you can see Php session files are just plain text files filled up with serialized SESSION arrays.

Hope it can help!

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- Filament.io 0 Flares ×