0

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.

odd_duck
  • 3,941
  • 7
  • 43
  • 85
  • 3
    Since you're using `session_id`, does that mean you've already started a session? That should already have set a cookie with that session id, no…? – deceze Aug 19 '19 at 11:54
  • https://stackoverflow.com/a/3684638/1461181 – odan Aug 19 '19 at 11:56
  • Actually it may not be a good idea to keep a session open for infinite duration after the browser is closed. Perhaps a small Windows may be given for improving the user experience and that too from a private computer. – Soumen Mukherjee Aug 19 '19 at 14:19

0 Answers0