Detect if PHP session exists
Facebook now offer subscriptions to users so you can get realtime updates on changes. If my app receives an update, I plan to store it in the database. I would also like to detect if their session exists. If it does then I could update the data in there too.
My session IDs are MD5(fb_id + secret) so I could easily edit their session. The question is how can I detect if the session exists.
Solution 1:
I use a combined version:
if(session_id() == '' || !isset($_SESSION) || session_status() === PHP_SESSION_NONE) {
// session isn't started
session_start();
}
Solution 2:
According to the PHP.net manual:
If
$_SESSION
(or$HTTP_SESSION_VARS
for PHP 4.0.6 or less) is used, useisset()
to check a variable is registered in$_SESSION
.
Solution 3:
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.
Solution 4:
Which method is used to check if SESSION exists or not? Answer:
isset($_SESSION['variable_name'])
Example:
isset($_SESSION['id'])