I'm running into this as well, and a setting in $_SESSION
is not an option for me. For PHP 5.3.8:
- If any session has been started with the request,
define('SID')
will return FALSE
, as well as $_SESSION
is unset.
- This is independent whether or not
session_id()
has been used to set a session id or not.
- After the first
session_start()
, SID
is defined and $_SESSION
is set to an empty array.
session_destroy()
does unset the session_id()
, it's an empty string then. SID
will remain defined (and set to it's previous value which might be an empty string). $_SESSION
is left unchanged. It will get reset/populated next time session_start
is called.
With these states, especially as session_id()
can be called in between to set the id for the next session, it's not possible to safely determine the session status with SID
, $_SESSION
and session_id()
.
"Trying" with session_start()
(e.g. with @
) might not be really helpful, as this will change the session status and changing the contents of $_SESSION
(and adding a set-cookie header if the cookie was not part of the request). It was not fitting in my case.
While I was running tests, I came across the behaviour, that you can not try to change the ini setting of session.serialize_handler
when the session is active, not even when you set it to the same value. Same is true for session.use_trans_sid
Docs which is more lightweight. This lead me to the following function:
/**
* @return bool
*/
function session_is_active()
{
$setting = 'session.use_trans_sid';
$current = ini_get($setting);
if (FALSE === $current)
{
throw new UnexpectedValueException(sprintf('Setting %s does not exists.', $setting));
}
$result = @ini_set($setting, $current);
return $result !== $current;
}
As far as I can see, the error is checking for active session status only (not disabled), so this should not return a false positive when sessions are disabled.
To get this function compatible with PHP 5.2, it needs a little modification:
/**
* @return bool
*/
function session_is_active()
{
$setting = 'session.use_trans_sid';
$current = ini_get($setting);
if (FALSE === $current)
{
throw new UnexpectedValueException(sprintf('Setting %s does not exists.', $setting));
}
$testate = "mix$current$current";
$old = @ini_set($setting, $testate);
$peek = @ini_set($setting, $current);
$result = $peek === $current || $peek === FALSE;
return $result;
}
Some sandbox.