Using sessions to store a shopping cart using Code

2019-09-16 15:25发布

问题:

I want to make an e-commerce website and don't want to force users have an account to purchase items, they can just do it whenever they feel like it.

Can I use the sessions class in CodeIgniter to do this, with the ability to keep a users session (i.e. their shopping cart items) for an extended period of time (maybe 6 months or a year)? I read the user guide on CI about sessions and it says it gives you the option to set sessions to not expire by stating the session_expire_on_close variable to false in the config file, which I'm guessing keeps the session running even after the user closes the browser.

Whenever a user visits the site, or adds something to their basket, I can start the session. Then when they leave and decide to come back, I can validate their shopping cart info from the sessions table in my database and give it back to them.

I also wanted to know if I should store shopping cart items in the ci_sessions table given as an example in the user guide in the user_data column? Would that be sufficient?

Just want to know if I'm heading in the right direction. Thank you

回答1:

Short answer: Yes, you're on the right path.

How I'd do it (some of this may be obvious):

  1. Add the session library to config/autoload.php so it starts automatically.

  2. Set up the 'Session Variables' section in config/config.php as needed - sess_expiration = some long time, sess_expire_on_close = false, use_database = true etc.

  3. To keep it simple, only store product IDs in the session. Below is a basic add_to_cart function as an example:

    public function add_to_cart($product_id) {
    
    // Whenever a user adds an item to their cart, pull out any they already have in there
    
    $cart_products = $this->session->userdata('cart_products');
    
    // Add the new item
    
    $cart_products[] = $product_id;
    
    // And put it back into the session
    
    $this->session->set_userdata('cart_products', $cart_products);
    
    }
    
  4. Use the product_ids from the session to pull out more details (e.g. product name) from your db and display them on screen.

Because CI keeps its own session_id this approach should automatically repopulate the session every time the user revisits your site, you shouldn't ever need to manually query the ci_sessions table or use standard PHP sessions.

The above isn't tested but hope it helps, shout if anything needs clarifying.



回答2:

CodeIgniter utilizes its own sessions (see this) which do not interfere with PHP sessions.

Therefore you could use the regular PHP session

session_start();

that creates or reopen the existing session, which ID is stored in a cookie (usually PHPSESSID). Then use that session instead of CodeIgniter's one

$_SESSION['MyData'] = 12345;

Maybe you could check in your CodeIgniter configuration that the cookie names do not collide in config.php, sess_cookie_name.