1

I want to redirect to my login page when my session is expired. What happens now:

When you are for example logged in and at the dashboard, you will see you're username in the right top corner. But when you don't do anything for 2 hours or so and then refresh you get an error that it's impossible to access an attribute 'username' of NULL. This comes because you're logged out... But how can I redirect to the login page when my session expires?

I know how I can increase the expire time but I don't know how I can redirect ..

nielsv
  • 6,540
  • 35
  • 111
  • 215

1 Answers1

6

check if username is set in your session

/* NATIVE PHP */
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit;
}

/* Symfony Syntax - thanks @Touki */
if (!$request->getSession()->get('username')) {
    return new RedirectResponse('login', 301);
}
MaiKaY
  • 4,422
  • 20
  • 28
  • And I just paste this in my general layout view? – nielsv Mar 27 '14 at 08:32
  • 1
    Just don't. Use the symfony's request abstraction instead. `$request->getSession()->get('username')` and `return new RedirectResponse('login', 301)` – Touki Mar 27 '14 at 08:50
  • 3
    You can place it at [$app->before()](http://silex.sensiolabs.org/doc/middlewares.html#before-middleware). – Ralf Hertsch Mar 27 '14 at 09:28
  • Thanks, but the 'username' attr doesn't exist. When I dump my $request->getSession() I get this: http://pastebin.com/7XQbJJ08 What should I use? – nielsv Mar 27 '14 at 10:19