1

Is there a way in PHP to get informations about all sessions of users connected on my server ?

For example :

  • User 1 logged in to my server with user info : login = "user1" and corpId= "test1"
  • User 2 logged in to my server with user info : login = "user 2" and corpId = "test2"

Each time a user is logged in, user info's are stored into $_SESSION .

Problem to solve :

When a user calls login API, I would like to be able to check if exist (or not) a session where a user is connected with the same corpId.

Test Example :

User 3 (corpId="test3") calls login API. Result = SUCCESS
User 4 (corpId="test2") calls login API. Result = FAILED 
(cause="ALREADY_EXISTING_SESSION)
Martin
  • 22,212
  • 11
  • 70
  • 132
wawanopoulos
  • 9,614
  • 31
  • 111
  • 166

1 Answers1

2

NOTICE: I think that the correct approach should be using a database to manage the connections, as pointed out by @Martin at the comments. I'm answering this just to give a different approach.

All running PHP sessions are saved in a file on a folder, until they are destroyed (take alook at this question). You could read all the session files in that folder, decode them and check if there is already a session file whith that corpId. Here is an example using the default save_path in CentOS.

<?php
session_start();

$session_files = glob("/tmp/sess_*");

$corpIds = array();
foreach($session_files as $session_file) {
    $session_data = @file_get_contents("$session_file");
    if($session_data === false)
        continue;
    session_decode($session_data);
    if(!in_array($_SESSION["corpId"], $corpIds))
        $corpIds[] = $_SESSION["corpId"];
}

print_r($corpIds);

?>
Community
  • 1
  • 1
Alvaro Flaño Larrondo
  • 5,516
  • 2
  • 27
  • 46