Detect if PHP session exists
I use a combined version:
if(session_id() == '' || !isset($_SESSION) || session_status() === PHP_SESSION_NONE) {
// session isn't started
session_start();
}
If $_SESSION
(or $HTTP_SESSION_VARS
for PHP 4.0.6 or less) is used, use isset()
to check a variable is registered in $_SESSION
.
isset($_SESSION['varname'])
If you are on php 5.4+, it is cleaner to use session_status():
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
PHP_SESSION_DISABLED
if sessions are disabled.PHP_SESSION_NONE
if sessions are enabled, but none exists.PHP_SESSION_ACTIVE
if sessions are enabled, and one exists.