简体   繁体   中英

Print all logged-in users in SESSION?

I have a SESSION that supports about 80 users, I want to print all their usernames and refresh the page every 60 seconds or so. I know how to refresh the page but <?php print_r($_SESSION['username']); ?> <?php print_r($_SESSION['username']); ?> is only printing the username associated with my personal session.

$_SESSION is unique to each user of the website, it uses cookies. print_r can only show the contents of the current $_SESSION. You would need a database to know all the users' name and Javascript to refresh the page.

Unfortunately sessions variables don't work like that.

For you to track each session, one method would be to log each login/connection to a MySQL table with a time stamp attached to it.

Then on your tracking page, have it delete the inactive users, then select the rest:

ie

mysql_query("DELETE FROM sessions WHERE time < " . time() - 60);

$result = mysql_query("SELECT * FROM sessions");

while ($row = mysql_fetch_assoc($result)) {

    echo $row['username'] . "<br />";
}

Then toss in a <meta http-equiv="refresh" content="60"> to refresh the page ever minute.

maybe you want to use something like "memcached" and use a variable there.

if you store the sessions in a separate folder (and not the default /tmp folder) you could do a list on that folder to find how many sessions are currently set on the server, knowing that it won't be a perfect exact number.

Database or memcached are probably your best possibiliies.

Session data is stored in files, depending on your application setup you can parse those files. Not a very proper solution in my opinion but it will do the trick.

You'll need to add a database table of currently logged in users, everytime somebody logs in, add their ID to the table, when they log out (or are timed out) remove the ID, you can save other info besides the ID, such as time, sessionID or IP address or a combination of these. It will give you a fairly good idea of who is online.

To take it one step further, you can have a field that holds the time of the last change of each page, every time you serve that person a page you overwrite this value, this can be used to log out people that just leave your site without doing a logout. For example, if they don't refresh the page for 30 mins you can log that person out of the site.

I would

  • Add a 'online' column in the users table.
  • Every time someone logs in or loads a page that they have access to, I would set the online column with the current timestamp.
  • When checking your online friend list, I'd query everyone who's been online in the pass 60 seconds
  • Then make sure your online friend list page updates every 60 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM