How to tell if a session is active?

Viewed 76549

Per request, there are a few different ways that you can tell whether or not a session has been started, such as:

$isSessionActive = (session_id() != "");

Or:

$isSessionActive = defined('SID');

However, these both fail if you start a session, then close it; session_id() will return the prior session's ID, while SID will be defined. Likewise, calling session_start() at this point will generate an E_NOTICE if you already have a session active. Is there a sane way to check if a session is currently active, without having to resort to output buffering, the shut-up operator (@session_start()), or something else equally as hacky?

EDIT: I wrote a patch to try to get this functionality included in PHP: http://bugs.php.net/bug.php?id=52982

EDIT 8/29/2011: New function added to PHP 5.4 to fix this: "Expose session status via new function, session_status"

// as of 8/29/2011
$isSessionActive = (session_status() == PHP_SESSION_ACTIVE);

EDIT 12/5/11: session_status() on the PHP manual.

7 Answers
Related