Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even acc
isset($_SESSION) isn't sufficient because if a session has been created and destroyed (with session_destroy()
) in the same execution, isset($_SESSION) will return true. And this situation may happen without your knowing about it when a 3rd party code is used. session_id()
correctly returns an empty string, though, and can be called prior to session_start()
.
I've always simply used
if (@session_id() == "") @session_start();
Hasn't failed me yet.
Been quite a long time using this.
NOTE: @
simply suppresses warnings.
Check if session exists before calling session_start()
if(!isset($_SESSION))session_start();
Store the session_id
in $_SESSION
and check against it.
First time
session_start();
$_SESSION['id'] = session_id();
Starts a session and stores the randomly given session id.
Next time
session_start();
$valid_session = isset($_SESSION['id']) ? $_SESSION['id'] === session_id() : FALSE;
if (!$valid_session) {
header('Location: login.php');
exit();
}
Starts a session, checks if the current session id and the stored session id are identical (with the ternary ? as replacement for the non-existing short circuit AND in php). If not, asks for login again.
In PHP there is something called the session name. The name is co-related to the cookie that will be being set if the session was already started.
So you can check the $_COOKIE
array if there is a session cookie available. Cookies are normally the preferred form to interchange the session id for the session name with the browser.
If a cookie already exists this means that a PHP session was started earlier. If not, then session_start()
will create a new session id and session.
A second way to check for that is to check the outgoing headers if the cookie for the session is set there. It will be set if it's a new session. Or if the session id changed.