49

I am using Magento and trying to save a value in the session as follows in its index.php file, but the value is not being retained.

$_SESSION['myvar'] = '1';

How do I do it?

Thanks

TheBlackBenzKid
  • 26,324
  • 41
  • 139
  • 209
Ali
  • 511
  • 1
  • 5
  • 5
  • I had the same issue when using `setcookie()` directly, as the `core/cookie` model handles setting those, and found it was overwriting my values. – DWils Feb 26 '14 at 22:10

4 Answers4

81

Let's say you want to save the value "Hello world" to the "welcome message" variable in the session. The code would be :

$inputMessage = 'Hello World';
Mage::getSingleton('core/session')->setWelcomeMessage($inputMessage);

Now you want to echo the "welcome message" somewhere else in your code/site.

$outputMessage = Mage::getSingleton('core/session')->getWelcomeMessage();
echo $this->__($outputMessage);
Hervé Guétin
  • 4,392
  • 4
  • 29
  • 36
37

Following the example given by Ali Nasrullah, I would do:

$session = Mage::getSingleton("core/session",  array("name"=>"frontend"));
// set data
$session->setData("device_id", 4);
// get data
$myDeviceId = $session->getData("device_id");

Make sure you include [Mage-root]/app/Mage.php befor calling the code above!

@Ali Nasrullah: Pass the value of device:id as second parameter of the setData function.

NiBa
  • 457
  • 1
  • 5
  • 6
  • 1
    I tried the above but couldn't get it to work. How to call /app/Mage.php. By default, index.php includes: require_once $mageFilename; Is that enough? – Remy Nagelmaeker May 06 '13 at 12:06
13
  Mage::getSingleton('core/session')->setMySessionVariable('MyValue'); 

  $myValue  =  Mage::getSingleton('core/session')->getMySessionVariable();

  echo $myValue;

 Take Look For More: 

Here are code to Get, Set, and Unset Session in Magento

Here are code to Get, Set, and Unset Session in Magento

Tero Lahtinen
  • 514
  • 6
  • 16
Jyotiranjan
  • 683
  • 8
  • 20
8
frontend: Mage::getSingleton('core/session')->setYourNameSession($session_value);

backend: Mage::getSingleton('admin/session')->setYourNameSession($session_value);
Ansyori
  • 2,807
  • 3
  • 29
  • 37