0

I am in a situation that I can't really resolve after reading many questions/solutions on here. Basically I am writing a small shopping cart application. I was finding a way to store which items a user adds to their cart and I ended up using $_SESSION.

The problem is that all saved cart data gets lost after they close the browser. I can't rely on $_COOKIE because I need to store each "Add" to cart as a new Array, and I couldn't find a way to do it with cookies (plus it has a limit or whatever), I am really confused to what to do now.

I am saving the cart data even for guests, and using a DB is not an option for me. Any suggestions?

James Arnold
  • 990
  • 1
  • 6
  • 15
Ahmed Fouad
  • 2,963
  • 10
  • 30
  • 54

5 Answers5

3

Why don't you store the cart in a database. Save a unique id in the users cookies (or if you have an authentication/login system, just use the user id). Storing it in a database also gives you the benefit of being able to see incomplete orders, which might be useful for statistics and for re-targeting marketing etc.

troelskn
  • 115,121
  • 27
  • 131
  • 155
2

I think it's standard practice for cart items to be lost when you close the browser.

You could try using HTML5 local storage:-

Local storage tutorial

Davos555
  • 1,974
  • 15
  • 23
1

You need to set a lifetime for your session cookie, which by default lives only until the browser is closed.

lanzz
  • 42,060
  • 10
  • 89
  • 98
1

As you mentioned, session does not persist when browser closes.

If database, or any kind of server-side storage, is not an option. You may consider save it in client-side with LocalStorage. Data in local storage persists even browser closes. Browser associates the domain name with your data.

Several things to note when using local storage.

First, local storage is in client side so you may need to pass back the data to server so PHP can manipulate it. (Assuming you still need server-side to handle the cart data.) Please refer to this stackoverflow post: PHP & localStorage;

Second, user can change the local storage without any restriction.

Third, it is not supported by IE until IE8. And if IE6/7 is your concern, you may need to fallback to cookies approach.

Community
  • 1
  • 1
Makzan
  • 356
  • 2
  • 10
0

Sessions are cleared when the browser is closed, so you would have to use cookies.

Have a look at this post to figure out how to store arrays in cookies: update cookie value in php

Troelskn's method is the one I would use however, storing a cart id in a database seems like the sensible thing to do :).

Community
  • 1
  • 1
Terry Seidler
  • 2,043
  • 15
  • 28