0

How can I add a value to a guest session?

I have tried with the following model session:

\Magento\Customer\Model\Session

and setter and getter for value like this:

$this->getCustomerSession()->setMyValue($token);

$this->getCustomerSession()->getMyValue(); 

However as far as I know customer is just for logged in customers, right? so how can I add a session value to guest session?

Greetings!

0

The session is customer-based, not user-based and since the guest and logged in user are different as far as Magento knows it's not possible.

The easiest way would be to use a cookie. This is stored on users' device and will be available both when the user is logged on and off.

$cookie = Mage::getSingleton('core/cookie'); $cookie->set('test', 'cos tam' ,time()+3600,'/'); $cookie->set('test123', 'cos tam12345' ,time()+3600,'/');

3600 is the number of seconds the cookie will be stored from the time it's set. In this case it's an hour but you can always increase it.

If, however, you're storing sensitive data don't put it in a cookie. Create a database table with the fields

  • ID
  • Key
  • IP
  • Value generate a random key for new visitors, store that in a cookie on their device and insert it in the table together with the value and users IP address. Now you can retrieve the data by checking for the cookie and its value and using the IP to ensure there's no session hijacking.

The script would look something like this https://pastebin.com/5dieE17Z

3
  • user ask about m2 not M1 – Amit Bera May 21 at 17:50
  • Thanks! do you know how to do this on Magento 2? if not it's ok I can search for cookie creation on Magento, thanks! – Oscar Vazquez May 21 at 20:36
  • You can apply my above method to M2. I did and it's working fine now – LitExtension Magento Migration May 25 at 4:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.