Php sessions: advanced session files managing practice

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 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
// 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){

// setting up php session garbage collection parameters
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 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:


[sourcecode language=”plain” gutter=”false”]

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 -- 0 Flares ×