override codeigniter native session

Posted on October 6, 2015 by Suresh Kamrushi in PHP
  

Struggling a lot with codigniter session issue. So I thought of using database for storing session but it did not solve my problem either (For Database approach click here ) than I thought of giving a try to have a library which override the codeigniter session class.

Here I am sharing how to create library which will override the codeigniter class without chagning exisitng code. Create a file inside “application\libraries” with “Session.php” and add the below code.

<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class CI_Session {

private $userdata;

public function __construct() {
if(!isset($_SESSION)) {
session_start();
}
}

function userdata($key) {
return isset($_SESSION[$key]) ? $_SESSION[$key] : "";
}

function set_userdata($newdata = array(), $newval = '') {
if (is_string($newdata)) {
$newdata = array($newdata => $newval);
}

if (count($newdata) > 0) {
foreach ($newdata as $key => $val) {
$this->userdata[$key] = $val;
}
}

$this->sess_write();
}

public function sess_write() {
foreach ($this->userdata as $key => $val) {
$_SESSION[$key] = $val;
}
}
function set_flashdata($newdata = array(), $newval = '') {
$this->set_userdata($newdata,$newval);
}

public function flashdata($key) {
return isset($_SESSION[$key]) ? $_SESSION[$key] : "";
}

function sess_destroy() {
unset($_SESSION);
session_unset();
}
}

The benefit of this approach is that above class override the CI session approach so there will be no code change and syntax and methods will be same. And you are using native $_SESSSION of php instead of cookies in CI.
So if DB approach is not working out for you go for this approach.
Enjoy!!!
My codeigniter version: 2.2.2

Tagged as , ,