Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has anyone created a PHP Session-like class in user code (not native)?

The native PHP Session functionality is great, but it's ultimately a singleton. There are times when you need to maintain state for multiple apps and in the scope of an already-started session (e.g. in an app framework). Technically one can stop/restart a session after changing session_name(), but this is impractical/impossible/unsafe within most apps. Using a shared session.save_path is also not an option if one app stores session data with a non-disk adapter.

There's no reason the functionality in native sessions can't be done in user code, so has anyone done this?

Update 1: CI_Session is indeed a userland implementation with some useful code, but it's highly coupled to CodeIgniter.

Update 2: Here's an API that would be great:

// setup
$saveHandler = new UserlandSession_SaveHandler_Files('5;/tmp');
$sess = new UserlandSession($saveHandler);
$sess->name('PHPSESSID2');
$sess->gc_maxlifetime = 86400;
$sess->setProxy($state); // passed by ref
// usage
$sess->start(); // stored string unserialized to $state
$state['foo'] = 'bar';
$sess->write_close(); // $state serialized to storage

Update 3: I've written an implementation for PHP5.3.

like image 725
Steve Clay Avatar asked May 19 '11 16:05

Steve Clay


People also ask

How can you create a session in PHP?

You can start a session in PHP by using the session_start() function. This function will, by default, first check for an existing session. If a session already exists, it will do nothing, but it will create one if there's no pre-existing session available.

What is the alternative of session in PHP?

The alternative to sessions is cookies (in fact, sessions are usually implemented using cookies). But cookies should only be used if you want to store small amounts of data.

What is session in PHP with example?

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.

How does session work in PHP?

PHP responds by sending a unique token that identifies the current session. This is known as the session ID. In all subsequent requests, the browser sends the session ID to say, "Hey, it's me again." All other data related to the session is stored on the web server. Only the session ID gets passed back and forth.


1 Answers

CodeIgniter has a session class that does not utilize native PHP sessions.

like image 181
Sean Walsh Avatar answered Nov 15 '22 00:11

Sean Walsh