36

On an e-commerce site with no username/login to persist cart data, would it be better to use the PHP $_SESSION variable or a browser cookie to persist items in the shopping cart? I am leaning toward $_SESSION since cookies can be disabled, but would like to hear thoughts from you.

Thank you in advance for your consideration.

5
  • 9
    What if you did both? The drawback with $_SESSION is that the session is cleared when the browser is closed. Use sessions, but attempt to populate the $_SESSION data from a cookie, if it's available.
    – Travesty3
    Sep 24, 2012 at 17:01
  • 1
    @Travesty3 you should add this as an answer. Sep 24, 2012 at 17:12
  • Do what @Travesty3 says, just remember: Do not store sensible information in cookies. They're travelling all the time back and forth from browser to server and are prone to be sniffed or hacked.
    – xPheRe
    Oct 1, 2012 at 6:36
  • 2
    @xPheRe: Think you meant "sensitive" information ;-)
    – Travesty3
    Oct 1, 2012 at 12:30
  • Storing it in the session is safe and thus fine, but @Xeoncross explains why it's probably more valuable to store only a unique ID in the session and store the actual data in your database.
    – caw
    Jul 13, 2016 at 0:07

6 Answers 6

51

Neither

No large sites would dare store a user's cart in a session or cookie - that data is just to valuable.

What customers are buying, when they select items, how many they purchase, why they don't finish the checkout, etc.. are all very, very important to your business.

Use a database table to store this information and then link it to the user's session. That way you don't lose the information and you can go back and build statistics based on users carts or solve problems with your checkout process.

Log everything you can.

Database Schema

Below is a simplified example of how this might look at the database level.

user {
    id
    email
}

product {
    id
    name
    price
}

cart {
    id
    product_id
    user_id
    quantity
    timestamp    (when was it created?)
    expired      (is this cart still active?)
}

You might also want to split the cart table out into more tables so you can track revisions to the cart.

Sessions

Normal PHP Sessions consist of two parts

  1. The data (stored in a file on the server)
  2. A unique identifier given to the user agent (browser)

Therefore, it's not $_SESSION vs $_COOKIE - it's $_SESSION + $_COOKIE = "session". However, there are ways you can modify this by using a single encrypted cookie which contains the data (and therefore you don't need an identifier to find the data). Another common approach is to store the data in memcached or a database instead of the filesystem so that multiple servers can access it.

What @Travesty3 is saying is that you can have two cookies - one for the session, and another that is either a "keep me logged in" cookie (which exists longer than the session cookie), or a copy of the data inside separate cookie.

7
  • That is an interesting approach. However, I should point out that it sounds like your answer is still in favor of the $_SESSION.
    – user1193509
    Sep 24, 2012 at 17:20
  • $_SESSION requires a matching $_COOKIE so that doesn't matter much. I actually use encrypted cookies for most of my stuff and skip the file/database/memcached $_SESSION wrappers since there is nothing more than a couple small data points in my cookies like the user_id.
    – Xeoncross
    Sep 24, 2012 at 17:21
  • I updated my answer with an example schema. The session has nothing to do with the cart. Sessions are only to know which user is interacting with your app - once you know that you use the user_id for everything else.
    – Xeoncross
    Sep 24, 2012 at 17:46
  • 1
    @nodirtyrockstar, you could do that too. Then, when the session expired the cart would automatically become "disabled" in a way because no one would have any more references too it. However, it's possible that two session_ids could be created over a period of time that matched - so you might want to prefix it with something if you are using it in the database.
    – Xeoncross
    Sep 24, 2012 at 17:55
  • 2
    i think this answer is more of a policy to a business than an answer to a technical question. you could just put the alternatives AFTER answering the technicality of it.
    – mavili
    Jan 22, 2014 at 7:40
9

As pointed out by Xeoncross, it is very important to store any possible information for analysis. So one should not entirely rely on sessions and cookies.

A possible approach is-

Use sessions if not logged in

If the user is not logged in, you can store and retrieve the cart items and wishlist items from session using $_SESSION in PHP

Use database when logged in

If the user is logged in then you can consider one of the two options -

  • Store the cart item or wishlist item in database alone
  • Store the cart item or wishlist item in database as well as in session (This will save some of your database queries)

When user logs in

When the user logs in, get all the cart items and wishlist items from the session and store it in the database.

This will make the data persistent even if the user logs out or changes the machine but till the user has not logged in, there is no way to store the information permanently so it will not be persistent.

Getting required data

Whenever you are trying to access cart or wishlist do the following check -

  • If the user is not logged in then look into session
  • If the user is logged in, query database if you are storing in the database alone, otherwise you can just look into sessions if you are keeping session updated along with the database
4
  • I know this post is over a year old, but I still have a question. What if the user creates a cart in the database, then creates another cart in a session (perhaps on different machine) and then logs in? I do not think it is a good idea to overwrite the current data in the database, but neglecting the new session cart is not an option either. What would be the best solution in this scenario? Jan 18, 2017 at 13:19
  • @user2988879 I think there is a mis-understanding. We will not be overriding current data in database when the user logs in. It is just an addition of new items in cart. These new items will be there in addition to already existing items unless the user deletes (removes) from cart.
    – MukeshD
    Jan 19, 2017 at 6:07
  • isn't that a bit weird in some scenarios? For example: a user creates a cart on their account and then creates a cart on another PC without logging in. The user then wants to check out with the new cart so they log in. The carts are added together and the user first has to delete all of the products they added in the first time before they can check out with the new cart. Jan 19, 2017 at 14:45
  • Well, in that case, you can keep a flag for the cart table in you db which will decide if a product is to be checked out or not. Then if user checks out with certain items and logs in, mark the flag for already existing items as false and the current items as true. Once the order is placed, switch the flag of other items to true again. You might need to handle a few other cases based on the flag and this approach will work.
    – MukeshD
    Jan 20, 2017 at 11:09
7

I would store it in a SESSION. My wish list is rather long, and I am afraid that it will not fit in the 4K storage that a COOKIE may occupy. It forces you set the session time out to a longer period.

note: there are some countries (like the Netherlands, where I am) that have very strict policies about cookies, and you may be forced by legislation to use Sessions.

2
  • 1
    What if you were simply storing Item ID's and Quantity values?
    – Daniel Li
    Sep 24, 2012 at 17:01
  • 25
    You have never seen my wife shopping!
    – JvdBerg
    Sep 24, 2012 at 17:02
4

Some points to help:

Cookies:

  • info is persisted untill the cookie expires (what can be configured by you);
  • tend to slow down the communication between server and client, since it has to be exchanged between the two in every request/response;
  • its an insecure form of storing data and easy to sniff;
  • they also have a limit to store data.

Session:

  • all information is persisted in the server, thus not been exchanged with the client.
  • because it is not shared across the network, its a bit more secure;
  • all info is lost when the session ends;
  • If you are hosting in a shared host, you may have problems with session ending in the middle of a operation due to a push on the resources by any of the sites hosted on the same server.

I would personally go with sessions, since I'm assuming to be a small/meddium auddience page. If it grows, you would be better with a simple DB structure to store this data, with a maintenance plan to get ridge of unnecessary data (eg: clients that choose some products but don't do the checkout).

2
  • 1
    "if you have many visitors, you will have a general server slowdown, because of the RAM amout needed to store all session variables;" -- I don't think this is an accurate statement. Session data doesn't get stored in RAM unless you've implemented a custom session handler that explicitly does so. And even in this case, you're probably using something like a dedicated memcached server, which will have a certain amount of RAM preallocated to it. Sep 24, 2012 at 17:18
  • 1
    Ok, you right. I was assuming some other thecnologies, maybe mistaken by me again, but as classic ASP and so. I will remove that sentence. Sep 24, 2012 at 17:21
3

You might consider using both.

The drawback with $_SESSION is that the session is cleared when the browser is closed.

Use sessions, but attempt to populate the $_SESSION data from a cookie, if it's available.

2

I would use a session. If a user has cookies disabled then the session won't be able to start as the session ID is stored on the user's machine in a cookie.

There are some settings you may want to look at in order to attempt to keep the sessions for longer.

  • Prevent the session cookie from being deleted when the user closes their browser by running session_set_cookie_params() with the lifetime parameter set. This function needs to run before session_start()

  • You may also want to extend how often sessions are cleared from the server by modifying the session garbage collection settings session.gc_probability, session.gc_divisor, session.gc_maxlifetime either in php.ini or using ini_set()

  • If you have other websites running on the server and you modify the above garbage collection settings you will need them set in php.ini so they apply to all websites, or if you are using ini_set() then you might also look at saving these sessions to a different directory than other websites by modifying session_save_path(). Again this is run before session_start(). This will prevent the garbage collection of other websites clearing up your extended sessions for one particular site.

  • I would also recommend setting the following session settings in php.ini session.entropy_file = /dev/urandom, session.entropy_length = 256, session.hash_function = sha512. That should give you a cryptographically strong session ID with an extremely tiny chance of collisions.

  • And make sure you have an SSL cert on your site to prevent man in the middle attacks against your session ID.

Obviously a user could still decide to manually clear all their cookies which will take the session ID cookie with it but that's a risk I'd be prepared to take. If I was halfway through a shopping cart system and hadn't checked out, I wouldn't go and clear my cookies. I still think sessions are better than just using plain cookies.

The data is secure enough so long as you are the only website that has access to your sessions directory and your session ID is strong. And by extending the server's session storage time your data can persist on the server.

There are further measures you could employ to make your sessions even stronger. Regenerate your session ID every 20 minutes, copying the data over. Also record session IDs against IP addresses in a database and check to see if a particular IP address attempts to send more than X number of session IDs in a given time to prevent someone trying to brute force a session ID.

You could also store the data in a database linked by the session ID, instead of in a session file on the server. However this is still reliant on a session ID which is stored in a cookie and could disappear at any time. The only way to truly be sure that a user doesn't lose their cart is by having them login first and storing in a database.

1
  • Although I said that PHP sessions need cookies, that's technically incorrect. Session IDs can be transferred between pages as GET variables in the URL. However you really don't want to be thinking about that option - it's inconsistent and generally nasty and not recommended.
    – batfastad
    Sep 24, 2012 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.