Check if PHP session has already been started

One of the challenges I came across is trying to figure out if a PHP session has already been started. I have an admin section on my site which operates using a PHP session. For the rest of the site, I wanted to display an “admin toolbar” if an admin was logged in. However, I did not want to call start_session on every page because that would initialize unnecessary sessions (hence using up resources on my server every time someone viewed a page). I only wanted to call session_start if a session was started/initialized in the admin portion of the site.

Turns out the solution is very simple. A typical setup of PHP sessions uses cookies to store the session ID on the person’s computer. All we need to do is check to see if this cookie is set on someone’s computer. If it is, call session_start () and check to see if the person has a successful login in the admin.

if (isset ($_COOKIE[session_name ()])) {
    session_start ();
    if (isset ($_SESSION['logged_in'])) {
        echo "You are an admin!";
    }
}

Of course in our admin section, we’d set the session variable $_SESSION[‘logged_in’] if there was a successful admin login.