How to store favorites into cookie without being logged in?

Hello,

I have a website with a listing, and the user can add items to favorites. I am using at the moment the setState command to save all the favorite information, but it will keep it just until the browser closes and the session ends.

I want to keep that information saved forever into a cookie, I know I can set allowAutoLogin to true to save user information into cookies, but the point is that users on my website don’t have an account so that will not work.

I must allow unregistered users to add items to favorites so they can see them again when re-visiting the website.

I am looking at the CHttpCookie but I don’t understand very well how it works, can anyone post an example or another way to accomplish the functionality that I need?

Thank you,

Alex.

As the amount of data you can store in a cookie is limited and has to be transmitted on every request i would go another way. Here the basic workflow:

  • Check if "userhash" key is set in a cookie

  • If not: Create a unique hash and save it to a cookie with a very long expire time

  • Read/Write the bookmarks for the user from/to a database using the hash to identify a user

Thank you for the recommendation I will try to understand how cookies work in Yii and save just an identifier of the user there, then all the data in the database.

The solution I have finally implemented is saving the session into database and the session_id into cookie:




<?php

'import' => array(

        'system.web.CHttpSession',

        'system.web.CDbHttpSession',

)

?>






<?php

'session' => array(

          'class' => 'CDbHttpSession',

          'sessionTableName' => 'yiisession',

          'connectionID' => 'db',

          'autoCreateSessionTable' => false,

          'timeout' => 2592000, // One month

          'autoStart' => true,

          'cookieMode' => 'only',

          'cookieParams' => array('lifetime'=>2592000,'path'=>'/'),

        ),

?>



I could not find a good simple example but got inspired from many posts and finally this works, maybe it needs more improvments but at the moment it solves my needs!

:)

Quick note: You don’t need these imports. Anything in system is imported automatically.