I followed the answer from here but it didn’t work for me:
Is possible to keep session even after the browser is closed?
Here is the code I tried:
$session_life = 2592000; // 30 days
session_set_cookie_params($session_life);
session_name('my_cart');
session_start();
// update the session_life
setcookie(session_name(),session_id(),time()+$session_life);
The problem with this is that every time the browser is closed I still get a new session_id, not the old one.
I am using a database to store the items in ‘my_cart’ and the session_id is just used to identify the user to show them their own cart.
What is the best way for me to keep the users cart alive for 30 days?
This is the code I ended up with:
$cart_name = "my_cart";
$cart_life = 2592000; // 30 days
session_start();
if (isset($_COOKIE[$cart_name])) {
session_id($_COOKIE[$cart_name]);
}
setcookie($cart_name, session_id(), time()+$cart_life);
I’ve had to do a similar thing with a site I wrote (allow a 30 minute period for a customer to enter a code)
Rather than use a cookie (as you can’t guarantee that the customer would be returning to the site in the same browser), I stored the expiry time for the code against the user’s record. That way, whatever browser they accessed the page from (e.g., starting from mobile, finishing on a desktop), they would always expire at the same time.
When the customer returns to the site, I compare the current time to the expiry time and act accordingly
As you’re already storing the customer’s basket, I would add an expiry time against the record and then run a compare when the customer returns. It’s quite easy to do:
If you want, you could even set the time of day to be a standard value (20:00) by using a bit more trickery in MySQL