Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a session is active? [duplicate]

Tags:

php

session

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.

like image 725
ken Avatar asked Sep 24 '10 15:09

ken


People also ask

Is session unique for every user?

Besides session hijacking, one session is always tied to just one user.

What is session status?

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.


2 Answers

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.

like image 87
ken Avatar answered Sep 23 '22 01:09

ken


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.

like image 23
Marc B Avatar answered Sep 25 '22 01:09

Marc B