Hey. I have a function that's run every time a user visits a page, to check that they are logged in. Here is the code:

function pageProtect($guestonly = false)
    if ($guestonly == false && !User::authenticated()) {
        $alerts = array();
        $alerts[] = array('type' => 'warning', 'message' => "You must sign in to view this page", 'dismissable' => false);
        //Put it in the session variable
        $_SESSION['alerts'] = $alerts;
        header('Location: /user/signin');
    }elseif ($guestonly == true && User::authenticated()) {
        header('Location: /dashboard');


When I visit /dashboard, it successfully redirects to /user/signin. However, there is nothing in the SESSION. No errors appear in the logs. The session has already been started, and if I try to start it again it produces an error. I also have another function that reads session data, and that works fine. The session set code is running, but why isn't it setting? This code is identical to code on another page where it does work.

Any help would be great!

3 Years
Discussion Span
Last Post by DJBirdi

You have redundant code so your $alerts variable is not being defined as expected.

$alerts = array(); // This isn't really needed if you're later going to use $alerts[]
$alerts[] = array(); // This is essentially making $alerts a multi-dimensional array because you're defining an array variable with another array

$alerts[] and $alerts = array() are the exact same thing. $alerts[] is used more in loops, so in your case the proper way would be just:

if ($guestonly == false && !User::authenticated()) {
    $alerts = array('type' => 'warning', 'message' => "You must sign in to view this page", 'dismissable' => false);

    //Put it in the session variable
    $_SESSION['alerts'] = $alerts;

I did mena to make it a multidimensional array. There can conceivebly be more than one error. It tutned out I just needed a die(); after the header redirect.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.