6

Could you tell me how to properly use sessions in ZF2? So far I have this code:

"session" =>
[
    "remember_me_seconds" => 2419200, 
    "use_cookies" => true,
    "cookie_httponly" => true
]

That's the session config I copied from some post here on stackoverflow. Now should I put this code into module.config.php in each module that uses sessions or in the Application module?

public function onBootstrap(EventInterface $Event)
{
    $Config = $Event->getApplication()->getServiceManager()->get('Configuration');
    $SessionConfig = new SessionConfig();
    $SessionConfig->setOptions($Config['session']);
    $SessionManager = new SessionManager($SessionConfig);
    $SessionManager->start();  
    Container::setDefaultManager($SessionManager);
}

Same problem with the onBootstrap() method of the Module class. Should this code go into each module's Module class or just once into the Application's Module class?

In both cases I have tried both approaches and I even tried putting this code into both modules at once, but the only thing I was able to accomplish was to set session variables in controller's constructor and then read them in actions/methods. I wasn't able to set a session variable in one action/method and then read it in another. If I remove the lines in which I set the variables in controller's constructor, I can no longer see these variables in the session. The session just behaves like it was created and deleted each time a page is requested.

Am I missing something? Please don't link me to any resources on the internet, I have read them all and they're not really helpful.

Charles
  • 50,943
  • 13
  • 104
  • 142

3 Answers3

14

You don't need to do any configuration to use sessions in Zend Framework 2. Sure, you can change settings, but if you just want to get up and running with sessions, then don't worry about it for now.

My apologies, but I am going to disregard your last sentence; about a month ago, I wrote an article about this subject with the purpose of showing how to quickly get started with using sessions in ZF2. It doesn't rank well in search engines, so chances are you haven't read it.

Here is a code snippet showing how it can be done. If you are interested in how it works behind the scenes, then please refer to the link above.

namespace MyApplication\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container; // We need this when using sessions

class UserController extends AbstractActionController {
    public function loginAction() {
        // Store username in session
        $userSession = new Container('user');
        $userSession->username = 'Andy0708';

        return $this->redirect()->toRoute('welcome');
    }

    public function welcomeAction() {
        // Retrieve username from session
        $userSession = new Container('user');
        $username = $userSession->username; // $username now contains 'Andy0708'
    }
}
ba0708
  • 10,180
  • 13
  • 67
  • 99
  • This doesn't work for me. I have read your article before - I said I've read everything on the internet about the topic. I may also tell you that doing `$s = new Container("User"); print_r($s);` prints the merged configuration of all modules in an endless while loop o.O –  Dec 27 '12 at 15:28
  • Strange. It works for me with the [Skeleton Application](https://github.com/zendframework/ZendSkeletonApplication). Did you base your application on this? – ba0708 Dec 27 '12 at 15:32
  • Yes, I did. I modified it slightly, renaming most of the folder structure to be CamelCase, however after doing so it still was working perfectly and I was able to properly implement models, controllers, views and unit tests for them - this also includes doing DB operations. The only things that doesn't work for me are the sessions. Now I will go check if your code works in an unmodified skeleton application. –  Dec 27 '12 at 15:37
  • I don't remember if I experienced the same thing with the infinite loop, but I think I recall experiencing something similar. I assume that you tried to set and access a session variable. Perhaps try `print_r($_SESSION)` after saving a session to see if the superglobal is overwritten correctly. If so, you will notice that it looks different than what is normally the case. – ba0708 Dec 27 '12 at 22:09
  • Yes, the `$_SESSION` superglobal is overwritten correctly and it always was. In the past I could also `print_r()` the Container object, but today I broke the code really hard and the bug I described earlier happens. When it comes to setting/accessing the variables, I can only access a variable if I had set it "in the same request" - e.g. if I set it in the Controller's constructor or called some method that sets a session variable. However when I navigate to another page the session data is lost. The same happens when I redirect to another page from within the code. –  Dec 27 '12 at 23:40
  • How does the `$_SESSION` array look like on the second page request (when the session data is saved on the first request)? Is it the same as after the data is saved in the first request? Can you access the data directly via `$_SESSION` like normally? – ba0708 Jan 04 '13 at 15:06
  • I actually took a really long break from this to learn CoffeeScript and Sass, but from what I remember I couldn't access a variable set in aAction() inside bAction(). I only could access variables that were set earlier (for example in the controller's constructor). Before I started to use ZF2 I have used a custom SessionHandlerInterface to save the sessions to database and my php.ini may be messy. I also use PHP 5.4.9, maybe this is the problem? –  Jan 10 '13 at 16:42
  • Okay, I managed to solve this. It all was caused because of the custom SessionHandlerInterface, messy php.ini and other settings. I actually reinstalled PHP, PHPUnit, Composer, PEAR and reset most cofigs to defaults and boom, it's solved. Thanks for help though. –  Jan 10 '13 at 23:10
  • @Andy0708 Thanks for this nice explanation on creating the sessions. i am working with multidimensional array in session container. I struck with the session storage. Could you pls explain more in detail on working with multidimensional session array ? thanks. :) – Paulraj Sep 07 '13 at 14:24
  • @Paulraj Thanks. :-) I have not done this myself, but did you try something like this: `$sessionContainer->order = array('id' => 123, 'items' => array(0 => 'item1', 1 => 'item2', 2 => 'item3'));`? Then I imagine that you can access an item like so: `$item1 = $sessionContainer->order['items'][0];`. You could probably use the object notation as well. Does that not work? – ba0708 Sep 08 '13 at 16:38
  • @Andy0708 I can able to create the array already as you mentioned. But while updating (appending another set of array to the same session container) its changed and not updated. thats my problem. – Paulraj Sep 08 '13 at 19:05
1

about session

Where do you want to store session (in mysql-db, in mongo-db,or in ram,..)? How to classify session into "namespace" like

$_SESSION["namespace"]["user"],
$_SESSION["namespace_1"]["user"]?

SessionManager

in Zend, Zend\Session\SessionManger help you to do many as what listed above

simple config for SessionManger

$sessionManager = new SessionManager();
$sessionStorage = new SessionArrayStorage();
$sessionManager->setStorage($sessionStorage);
//you can add more config, read document from Zend
$sessionContainer = new Container("ABC", $sessionManager);
$sessionContainer->offsetSet("user", "lehoanganh25991");

when you call new Container without any SessionManager config

$sessionContainer = new Container("abc");

behind the scence, Zend create a default SessionManager, then pass it into Container

SessionArrayStorage, $_SESSION

SessionArrayStorage in Zend can work with $_SESSION, we can access to user above through

$_SESSION["ABC"]["user"]

if you set other storages like mysql-db, mongo-db, in ram,.. access through $_SESSION may not work

access session

in Module A, set session

How can we access it in Moudle B? where $sessionContainer variable @@?

it quite weird, but when you want to access to the this container, create a new one with SAME CONFIG

$sessionManager = new SessionManager();
$sessionStorage = new SessionArrayStorage();
$sessionManager->setStorage($sessionStorage);
$sessionContainer = new Container("ABC", $sessionManager);
//access
var_dump("get user from \$sessionContainer", $sessionContainer->offsetGet("user"));

review demo on github: https://github.com/hoanganh25991/zend-auth-acl/tree/d0a501e73ac763d6ef503bbde325723ea1868351

(through commits, the project changed, access it at this tree)

in FronEnd\Controller\IndexController
in AuthAcl\Module.php
in AuthAcl\Service\SimpleAuth
i acces same session at different places
Anh Le Hoang
  • 81
  • 1
  • 4
0
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;

class IndexController extends AbstractActionController
{   
    // set session values
    public function indexAction()
    {
       $session = new Container('User'); // name your session here by replacing User
$user_session->offsetSet('user_name', "your user name"); // set your session user name
$user_session->offsetSet('user_id', "1232"); //set your session user id
    }

// function to get values from session
  public function getdataAction(){
    $session = new Container('User');
    $user_name= $user_session->offsetGet('user_name'); // get user name from the session
   $user_id= $user_session->offsetGet('user_id'); // get user id from the session
}

// function to unset session values
 public function unsetdataAction(){
   $session = new Container('User');
    $user_session->offsetUnset('user_name'); // unset user name
        $user_session->offsetUnset('user_id');
}
}