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.
Besides session hijacking, one session is always tied to just one user.
Sessions or session handling is a way to make the data available across various pages of a web application. The session_status() function returns the status of the current session.
See edits to the original question; basically, PHP 5.4 and above now has a function called session_status()
to solve this problem!
"Expose session status via new function, session_status" (SVN Revision 315745)
If you need this functionality in a pre-PHP 5.4 version, see hakre's answer.
I worked around this by adding a couple wrapper functions around the various session creation/closing/destroying functions. Basically:
function open_session() { session_start(); $_SESSION['is_open'] = TRUE; } function close_session() { session_write_close(); $_SESSION['is_open'] = FALSE; } function destroy_session() { session_destroy(); $_SESSION['is_open'] = FALSE; } function session_is_open() { return($_SESSION['is_open']); }
Hackish, but accomplished what I needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With