Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access active sessions in PHP

Tags:

php

session

How can I get a list of all active PHP sessions on a server and access them from within one user's instance?

The motivating case is displaying a list of all currently active users on the site, where usernames are stored in each user's PHP session.

Note: I know that I can create my own state via a database (or even the filesystem), but I'm looking for a way to utilize the built-in PHP session mechanisms.

like image 651
G__ Avatar asked Aug 06 '10 18:08

G__


2 Answers

Seeing the responses, though it's possible, it doesn't mean you should do it. The format in which the sessions are stored is not documented and may change at any time (even between minor versions).

The correct way to do this is to implement your own session handler. It's not that hard, really.

like image 172
2 revs, 2 users 91% Avatar answered Sep 19 '22 06:09

2 revs, 2 users 91%


Session List

<?php
print_r(scandir(session_save_path()));
?>

Check for a Specific Session

<?php
session_start();
echo (file_exists(session_save_path().'/sess_'.session_id()) ? 1 : 0);
?>

Time Session File Last Changed

<?php
session_start();
echo filectime(session_save_path().'/sess_'.session_id());
?>

As has been done to death, already, it isn't best-practice to handle sessions this way but if it's needed, those will work without the need to check/modify the session storage path (useful if you switch to another server with a different configuration).

like image 22
Alastair Avatar answered Sep 19 '22 06:09

Alastair