简体   繁体   中英

Working with regenerating session id in PHP/CodeIgniter

I'm using CodeIgniter's Session class to manage my sessions for a cart/checkout system. The session data is being stored in the database and the session id is stored in a cookie. All cart information is retrieved via AJAX and is kept in the session, along with the session id.

Right now I am using the session id that PHP/CodeIgniter generates as a way to keep track of users. Users do not log in to the site and the store and the cart/checkout system are on different domains so this is the only thing that is tying them to their cart that is stored in the session/database. I use this session id in hidden fields on forms and as a parameter in links so that it gets sent to the server on any request (add item, remove item, view cart, etc...)

CodeIgniter lets you set a time for regenerating the session id, right now I have it set to 10 minutes. I had it at the default but that was too short because if the user sat at the page for too long, the session id that was dynamically written to the links and forms would be out of date and no longer tied to their cart data.

This is obviously not a great solution. What is the best way to allow for regenerating session ids at a lower interval but still keep users tied to their cart data even if the user waits 10+ minutes (without a page refresh) to do an action?

Don't use the session id's in the database. The cart should persist across sessions, so you need to store the cart in relation to the user, not the session. I also would not be putting the session id in fields as a hidden field. The benefit of sessions is you can store them server side.

Store the cart in the database, don't load the whole thing into session.

Method #1

A user can be given an "active" cart in the database.

User -> (has many) Cart

This cart is then updated by adding items to it

/cart/add/{id}        -> Verify prices / quantities

This cart is not linked to the session, the session is only controlling which user is logged in. When they checkout the cart is set from "active" to "ordered" and a new "active" (but empty) cart is created. Carts will persist in the database between sessions, and a full history can be made available.

Method #2

Store the entire cart in session, not backed against the database. This would make some things simpler (adding / removing items aren't DB operations) but it also won't persist across sessions. When a user checks out write the cart to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM