Part of the EllisLab Network
   
1 of 3
1
php session library
Posted: 19 April 2006 03:22 PM   [ Ignore ]  
Lab Assistant
Avatar
RankRank
Total Posts:  208
Joined  04-18-2006

Here is a php-based session library, including a namespace feature.

(BTW, is there a better place to contribute code to CI I don’t know about?)

It uses the PHP $_SESSION superglobal to read/write session data.
Further session management options (file/db container, etc) are then controlled
from the usual methods via php.ini.

like any CI library, you can either autoload it:

configs/autoload.php

$autoload['core'] = array('phpsession');

Or, load it manually inside any controller method:

$this->load->library('phpsession');

Example of usage from controller method:

function mymethod() {
   $this
->load->library('phpsession');
   
// save a variable to the session
   
$this->phpsession->save('foo','bar');
   
// save a variable in a namespace (other than default)
   
$this->phpsession->save('foo','bar','mynamespace');
   
// read a var from the session
   
$foo = $this->phpsession->get('foo');
   
// get var from a namespace
   
$foo = $this->phpsession->get('foo','mynamespace');
   
// get all session vars (from default namespace)
   
$all = $this->phpsession->get();
   
// get all session vars from given namespace
   
$all = $this->phpsession->get(null,'mynamespace');
   
// clear session var
   
$this->phpsession->clear('foo');
   
// clear all vars (default namespace)
   
$this->phpsession->clear();
   
// clear all vars in given namespace
   
$this->phpsession->clear(null, 'mynamespace');

   
// rest of your method
   
$this->load->view('myview');
}

To install phpsession, just drop these two files in the appropriate places:

application/init/init_phpsession.php

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

if ( !
class_exists('PhpSession'))
{
     
require_once(APPPATH.'libraries/phpsession'.EXT);
}

$obj
=& get_instance();
$obj->phpsession = new PhpSession();
$obj->ci_is_loaded[] = 'phpsession';

?>

application/libraries/phpsession.php

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

class
PhpSession {

    
// constructor
    
function PhpSession() {
        session_start
();
    
}
    
    
function save($var, $val, $namespace = 'default') {
        $_SESSION[$namespace][$var]
= $val;
    
}
    
    
function get($var = null, $namespace = 'default') {
        
if(isset($var))
            return isset(
$_SESSION[$namespace][$var]) ? $_SESSION[$namespace][$var] : null;
        else
            return isset(
$_SESSION[$namespace]) ? $_SESSION[$namespace] : null;
    
}
    
    
function clear($var = null, $namespace = 'default') {
        
if(isset($var))
            unset(
$_SESSION[$namespace][$var]);
        else
            unset(
$_SESSION[$namespace]);
    
}
    
}
?>
 Signature 

http://www.motortopia.com/
http://www.huskerlocker.com/
http://www.phpinsider.com/

Profile
 
 
Posted: 19 April 2006 04:28 PM   [ Ignore ]   [ # 1 ]  
Lab Assistant
Avatar
RankRank
Total Posts:  130
Joined  04-14-2006

I like this. Very clean. Would be fairly easy to extend it to use a custom handler (and store sessions in database).

 Signature 

CIForge.com - CodeIgniter Community Source Hosting

Profile
 
 
Posted: 22 April 2006 10:17 AM   [ Ignore ]   [ # 2 ]  
Grad Student
Rank
Total Posts:  61
Joined  03-13-2006

Great work Mohrt!

Profile
 
 
Posted: 22 April 2006 10:49 AM   [ Ignore ]   [ # 3 ]  
Summer Student
Avatar
Total Posts:  21
Joined  04-16-2006

Thanks Mohrt!

 Signature 

http://axgle.com

Profile
 
 
Posted: 22 April 2006 02:20 PM   [ Ignore ]   [ # 4 ]  
Research Scientist
Avatar
RankRankRankRankRankRank
Total Posts:  5968
Joined  11-23-2003

Thank you for the contributions you have made.  I am going to try out your Ajax examples here pretty soon.

Profile
 
 
Posted: 23 April 2006 08:28 AM   [ Ignore ]   [ # 5 ]  
Grad Student
Rank
Total Posts:  61
Joined  03-13-2006

Does anybody else get this error? I cant seem to figure out what is wrong!

A PHP Error was encountered

Severity
: Warning

Message
: require_once(C:/Work/HelpDesk/system/application/libraries/phpsession.php) [function.require-once]: failed to open stream: No such file or directory

Filename
: init/init_phpsession.php

Line Number
: 6

init_phpsession.php is in the init folder and phpsession.php is in the libraries forlder so what is wrong?
This happens whe i autoload the lib

My CI ver 1.3.2

Profile
 
 
Posted: 23 April 2006 08:32 AM   [ Ignore ]   [ # 6 ]  
Grad Student
Rank
Total Posts:  61
Joined  03-13-2006

Same thing happens when i load the lib from a Controller :(

Profile
 
 
Posted: 23 April 2006 08:38 AM   [ Ignore ]   [ # 7 ]  
Summer Student
Total Posts:  30
Joined  04-05-2006
Mayowa - 23 April 2006 08:28 AM

init_phpsession.php is in the init folder and phpsession.php is in the libraries forlder so what is wrong?

Did you put them in the libraries and init folders inside the application folder? You may have to create these folders if they don’t exist. See the manual about creating core libraries for clarification…

 Signature 

http://www.kelvinluck.com/

Profile
 
 
Posted: 23 April 2006 08:42 AM   [ Ignore ]   [ # 8 ]  
Grad Student
Rank
Total Posts:  61
Joined  03-13-2006

Vitch, Yes i did. Both files are there as a matter of fact if you pay close attention to the error message you will notice that the Error is comming from inside the init_phpsession.php

Profile
 
 
Posted: 23 April 2006 08:54 AM   [ Ignore ]   [ # 9 ]  
Summer Student
Total Posts:  30
Joined  04-05-2006

Oh, sorry - it looked to me like the error I get when I put the files in system/init and system/libraries rather that system/application/init and system/application/libraries…

So does the file C:/Work/HelpDesk/system/application/libraries/phpsession.php exist on your computer?

 Signature 

http://www.kelvinluck.com/

Profile
 
 
Posted: 23 April 2006 09:40 AM   [ Ignore ]   [ # 10 ]  
Grad Student
Rank
Total Posts:  61
Joined  03-13-2006

vitch you are a genius!
The problem was that i had modified the original code to point to the system/libraries folder. but the version i’m working with hadnt been modified… i feel so foolish.

Thank you.

Profile
 
 
Posted: 01 May 2006 04:20 PM   [ Ignore ]   [ # 11 ]  
Lab Assistant
Avatar
RankRank
Total Posts:  130
Joined  04-14-2006

I’ve updated this to include support for ‘flash’ variables, as described in this thread

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

class
phpsession {
var $_flash = array();

    
// constructor
    
function PhpSession() {
        session_start
();
        
$this->flashinit();
    
}
    
    
/* Save a session variable.
     * @paramstringName of variable to save
     * @parammixedValue to save
     * @paramstring  (optional) Namespace to use. Defaults to 'default'. 'flash' is reserved.
    */
    
function save($var, $val, $namespace = 'default') {
        
if ($var == null) {
            $_SESSION[$namespace]
= $val;
        
} else {
            $_SESSION[$namespace][$var]
= $val;
        
}
    }
    
    
/* Get the value of a session variabe
     * @paramstring  Name of variable to load. null loads all variables in namespace (associative array)
     * @paramstring(optional) Namespace to use, defaults to 'default'
    */
    
function get($var = null, $namespace = 'default') {
        
if(isset($var))
            return isset(
$_SESSION[$namespace][$var]) ? $_SESSION[$namespace][$var] : null;
        else
            return isset(
$_SESSION[$namespace]) ? $_SESSION[$namespace] : null;
    
}
    
    
/* Clears all variables in a namespace
     */
    
function clear($var = null, $namespace = 'default') {
        
if(isset($var) && ($var !== null))
            unset(
$_SESSION[$namespace][$var]);
        else
            unset(
$_SESSION[$namespace]);
    
}
    
    
/* Initializes the flash variable routines
     */
    
function flashinit() {
        $this
->_flash = $this->get(null, 'flash');
        
$this->clear(null, 'flash');
    
}
    
    
/* Saves a flash variable. These are only saved for one page load
     * @paramstringVariable name to save
     * @parammixedValue to save
     */
    
function flashsave($var, $val) {
        $this
->save($var, $val, 'flash');
    
}
    
    
/* Gets the value of a flash variable. These are only saved for one page load, so the variable must
     * have either been set or had flashkeep() called on the previous page load
     * @paramstringVariable name to get
     */
    
function flashget($var) {
        
if (isset($this->_flash[$var])) {
            
return $this->_flash[$var];
        
} else {
            
return null;
        
}
    }
    
    
/* Keeps the value of a flash variable for another page load.
     * @paramstring(optional) Variable name to keep, or null to keep all. Defaults to keep all (null)
     */
    
function flashkeep($var = null) {
        
if ($var != null) {
            $this
->flashsave($var, $this->flashget($var));
        
} else {
            $this
->save(null, $this->_flash, 'flash');
        
}
    }
}
?>

I started to modify the flash library to support phpsession, but it would have involved rewriting some of phpsession so I figured this was simpler.

I’m using it to remember the url when logging in.

Eg, At the top of any page that requires a login (or in the constructor of the controller, if the whole thing requires login), I have:

$this->phpsession->flashsave('returnurl', $this->uri->current_uri() );
redirect('user/login');

User::login() is my login controller, and the relevant part of the code to make use of the flash variables is:

if ($login_successful) {
   
if ($url = $this->phpsession->flashget('returnurl') ) {
      redirect
($url);
   
} else {  
      redirect
('');
   
}
}
else {
   $this
->phpsession->flashkeep('returnurl');
}

This makes it so when they go to a password-required page, eg, “foo/bar”, they are redirected to the login page. Upon successful login, they are redirected back to “foo/bar”, which makes for a nice user experience - eg, they can bookmark that page, and even if they need to login, it doesn’t mess it up.

 Signature 

CIForge.com - CodeIgniter Community Source Hosting

Profile
 
 
Posted: 23 May 2006 11:07 AM   [ Ignore ]   [ # 12 ]  
Summer Student
Total Posts:  13
Joined  03-27-2006

It would be really nice if I could pass this an associative array!

Profile
 
 
Posted: 29 May 2006 01:28 AM   [ Ignore ]   [ # 13 ]  
Lab Assistant
RankRank
Total Posts:  109
Joined  05-25-2006

to Greg:
I see no difference between usual session variable and flash variable. Flash variable always remains in session.  There should be some ‘unset’ in method flashinit().

 Signature 

CI 1.5 on WAMP (W2k Pro, Apache 2, MySQL 4.1, PHP 4.4)

Profile
 
 
Posted: 29 May 2006 07:45 AM   [ Ignore ]   [ # 14 ]  
Lab Assistant
Avatar
RankRank
Total Posts:  130
Joined  04-14-2006

Hm, dunno how I missed that one.. thanks! (Updated in post)

 Signature 

CIForge.com - CodeIgniter Community Source Hosting

Profile
 
 
Posted: 08 June 2006 01:43 AM   [ Ignore ]   [ # 15 ]  
Summer Student
Total Posts:  1
Joined  06-08-2006

I am trying the code with the Flash Variables and it doesn’t work, the flash variables are always empty.  Is there something I need to do besides load the PHPsessions from above?  The rest of it works, but this part doesn’t.  I’d really like to use them especially for the login at least.

Profile
 
 
   
1 of 3
1
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 819, on March 11, 2010 11:15 AM
Total Registered Members: 120353 Total Logged-in Users: 37
Total Topics: 126480 Total Anonymous Users: 2
Total Replies: 665156 Total Guests: 373
Total Posts: 791636    
Members ( View Memberlist )
Newest Members:  ejsexton82jackmarioRanjanjoyMihai NorthThatchVagariPatient ShareNixnizviVadotlogik