How to set a maximum of time to keep item in a session array

Hi,

I have a shopping cart and sometime I have to buyer that have the same items in their shopping cart and that cause and issue (selling twice the same items).

I know how to remove the item from the library or DB when a buyer add it to their shopping cart, but if the user leaves the web site without buying the item, I need a way to put back the item.

Is there a way to something like this in PHP ? to make sure that 2 users won’t buy the same items and/or to allow a maximum of X times that an item can be kept in the cart.

Thanks

Y.

This is a non-trivial issue and there is, sadly, no ready-made built-in-PHP method for this.

What you will have to do is to write your own session handler, driven by database. This has plenty of advantages, one of them being that PHP won’t garbage-collect your session data without you knowing about it. The other advantage is that you will be able to fine-tune how your sessions work.

This comes at a price, however, and the price is in raw code: writing a session handler, whilst being an awesome thing to do, can taketime.

Start by creating the following MySQL table:

sessions id INTEGER NOT NULL, primary key, auto increment sid VARCHAR(40), unique last_active DATETIME data TEXT

The idea is obvious: you cookie your users with a unique token and insert a session in the DB. The DB does stuff with it. How you store stuff is up to you.

The important part for you is what is called garbage collection. You can check which sessions are out of date using the last_active field in each session row. Every request on the page, check which ones are over, and when they are over, put the items back from the session to the store.
If you have a high-visit website, instead of doing it every request, do it every x requests so that you get one update per second or more at peak time.

Sponsor our Newsletter | Privacy Policy | Terms of Service