title: Slim 2: How do I use session cookie in the middleware?
body: <p>After looking around online, I still don't understand how session works in Slim2. The examples of Slim SessionCookie is extremely rare. Almost none. And that I am stuck with what I can get from the doc.</p>
  
  <p><a href="http://docs.slimframework.com/sessions/cookies/" rel="nofollow">http://docs.slimframework.com/sessions/cookies/</a></p>
  
  <p>"The second argument is optional; it is shown here so you can see the default middleware settings. The session cookie middleware will work seamlessly with the $_SESSION superglobal so you can easily migrate to this session storage middleware with zero changes to your application code.</p>
  
  <p>If you use the session cookie middleware, you DO NOT need to start a native PHP session. The $_SESSION superglobal will still be available, and it will be persisted into an HTTP cookie via the middleware layer rather than with PHP’s native session management."</p>
  
  <p>So, for instance,</p>
  
  <pre><code>use Slim\Slim;
  use Slim\Middleware\SessionCookie;
  
  $app = new Slim();
  
  $app-&gt;add(new SessionCookie(
      array(
          'expires' =&gt; '20 minutes',
          'path' =&gt; '/',
          'domain' =&gt; null,
          'secure' =&gt; false,
          'httponly' =&gt; false,
          'name' =&gt; 'slim_session',
          'secret' =&gt; 'CHANGE_ME',
          'cipher' =&gt; MCRYPT_RIJNDAEL_256,
          'cipher_mode' =&gt; MCRYPT_MODE_CBC
      )
  ));
  
  $app-&gt;get('/admin', function () use ($app) {
      // Check for session.
      if (session: user exist) { 
          echo "Hello Admin";
      } else {
          $app-&gt;redirect('login');
      }
  });
  
  $app-&gt;run();
  </code></pre>
  
  <p>How can I set session: user to the middleware and retrieve it?</p>
  
  <p>This is how I would do in native PHP,</p>
  
  <p>bootstrap.php</p>
  
  <pre><code>// Check username and password, if they match with the ones in db, 
  // then get the hashed key in the user row. 
  // Last, store the key in the session.
  $_SESSION["user"] = 'hashedkeyxxxx';
  </code></pre>
  
  <p>admin.php,</p>
  
  <pre><code>// Check if the session exist when the user want to access the admin only pages.
  if ($_SESSION["user"]) { 
      echo "Hello Admin";
  } else {
      // redirect
  }
  </code></pre>
  
  <p>How can I do this with Slim then?</p>