I am using my own session_set_save_handler()
function to store my php sessions into a database. I then combine this with php's setcookie()
so that I can restore the session if the user comes back having closed their browser.
My code is like so:
include("session.class.php"); // stores the session_set_save_handler function
$session = new Session(); // starts a new PHP session
$session_id = session_id();
// if cookie DOES NOT already exists
if( !isset($_COOKIE['cart']) )
{
// set cookie
$expires = 600 + time(); // set expiry of 10 minutes
setcookie('cart', $session_id, $expires, NULL, NULL, true, true);
// define session variables
$_SESSION['cart_id'] = $id_of_the_cart_quote;
// now do something with the cart...
}
// cookie exists so restore session from DB
else
{
$prev_session_id = $_COOKIE['cart'];
$prev_sess = $session->_read( $prev_session_id ); // get the session data from DB
if( $prev_sess != '' ) // if session data from DB isn't empty
{
// _decode_session_data() is a custom function which decodes session data string
$decoded = $session->_decode_session_data( $prev_sess );
$cart_id = $decoded['cart_id'];
// now load the cart from this id...
}
else
{
// handle error of empty session data
}
}
This works and means I can restore the cart from the database if the cookie hasn't expired.
However are there any security implications with this method of storing the session id in a cookie? Is this bad practice or should any encryption be used?
The data stored on the database with this session is only ever the cart id - a numeric integer. From this it just loads up the cart quote (from another database table). There will not be any customer / card / username / password data attached or stored with this.