Prerequisites
What will you learn?
- Store data in a session key
- Retrieve data from a session key
Tutorial
Sessions basics
Sessions provide a way to associate information with individual visitors on your website. Each session has a unique identifier to allow communication between server and user. They are commonly used to store data of the users logged-in with your web application.
That data is stored on the server, which is the key difference with cookies; they are stored on the clients machine instead. The functionality is therefor similar with SpoonCookie, both use the same set/get principle:
The example below stores the value 'bar' in a session variable named 'foo'.
// required classes
require_once 'spoon/spoon.php';
// start the session
SpoonSession::start();
// set session variable 'foo' with value 'bar'
SpoonSession::set('foo', 'bar');
The example below retrieves the data stored in the session key named 'foo', if it exists.
// required classes
require_once 'spoon/spoon.php';
// check if the key exists
if(SpoonSession::exists('foo'))
{
// show the output of get()
Spoon::dump(SpoonSession::get('foo'));
}
will output:
string(3) "bar"
SpoonSession::exists() accepts multiple keys to look up, but will only return true if all keys in $_SESSION were found.
Destroying a session
To let users log out of your web application, you can use SpoonSession::destroy(). In the example below the session ID will become unavailable after the destroy() occurs because there is no session set. It will return a SpoonSessionException.
// required classes
require_once 'spoon/spoon.php';
// show the session ID
Spoon::dump(SpoonSession::getSessionId(), false);
// destroy session - logs out the user by destroying his/her session
SpoonSession::destroy();
// attempt to show the session ID - this will trigger an exception
Spoon::dump(SpoonSession::getSessionId());
Conclusion
SpoonSession does not differ much from the standard session functionality in PHP, save for a few convenient extras and small timesavers.