I need to set a variable session in Magento, do I do just procedural PHP or is there a proper way in Magento 2 ?

Example :

$_SESSION['myKey'] = "00001";

@AnsarHunsain code help me, but I can't get my value into another page. My page and my block are on the same module than the block where I've defined getCheckoutSession.

I have this error with this :

  echo $block->getCheckoutSession()->getCommande();

Call to a member function getCommande() on null


You can use to set and get custom session value like below

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

    $catalogSession = $objectManager->get('\Magento\Catalog\Model\Session');
    //customerSession  \Magento\Customer\Model\Session;
    //checkoutSession = \Magento\Checkout\Model\Session;

    // set session variables and their value

    // print session variables value
    echo $catalogSession->getMyName(); // Test

    // Unset session

You can use dependency injection also like below

namespace Vendor\Module\Block;
class Session extends \Magento\Framework\View\Element\Template
    protected $_catalogSession;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\Session $catalogSession,
        array $data = []
        $this->_catalogSession = $catalogSession;
        parent::__construct($context, $data);

    public function _prepareLayout()
        return parent::_prepareLayout();

    public function getCatalogSession() 
        return $this->_catalogSession;

Use below code in phtml file

echo $block->getCatalogSession()->getMyName(); // Test
| improve this answer | |
  • isn't Object manager to avoid ? And can I replace "setMyName" by "setAnythingElse" ? – Morgan Tartreau Sep 19 '18 at 9:03
  • yes you can use dependency injection at the place of object manager and yes you can use setAnythingElse – Ansar Husain Sep 19 '18 at 9:05
  • Ok thanks, I think it's gonna be ok, I have I any trouble I'll come back – Morgan Tartreau Sep 19 '18 at 9:07
  • Should I do this in controller or in a block php file ? – Morgan Tartreau Sep 19 '18 at 9:13
  • if you want to display this session value in phtml file then do it in block specially other wise you can use it anywhere – Ansar Husain Sep 19 '18 at 9:14

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.