tags:

views:

861

answers:

4

I'm looking for an easy (no database) method of listing how many users are active on a website. The easiest way I can come up with is by counting the number of open sessions.

This code should work:

$number_of_users = count(scandir(ini_get("session.save_path")));

Of course it won't because of the security constraints on that directory (as there should be!!). Does anyone know another way to access this number without changing directory permissions.

Note: I'm looking for an option that does not involve databases or reducing the security on PHP sessions.

End Note: For anyone coming to this question, I ended up using a cronjob (running every minute) from root that did something similar to:

ls /var/lib/php5/ | wc -l > /var/www/sessioncount

Make sure the /var/www/sessioncount file is readable by the apache user. Then you can just read the file in PHP:

$number_of_users = file_get_contents("/var/www/sessioncount");
A: 

Is there no other way to access the sessions than via the filesystem?

Matt
A: 

You can't access that directory from a PHP script without posing a security risk.

The easiest way to achieve what you want is using a database. Just store the ip and the timestamp, and then SELECT based on the timestamp to get the number of active users on your website.

L. Cosio
I wanted a no database method. Thanks
St. John Johnson
+2  A: 

Easy does not mean no database in this case. Also relying on session to see how many users are active is not reliable.

If you wanted to go that route, you could do a cronjob that is run by a safe process every few minutes and saves that count into a file or db, which PHP reads.

But i recommend going the database route.

Ólafur Waage
Database method is the slowest and biggest throttle for any web application. My goal is to reduce the number of database queries to a minimum. I like the idea of the cronjob, or at least a running process.
St. John Johnson
+2  A: 
<?
// you must set your own accessible session path atop every page.
session_save_path("/home/some/other/location/"); # SECURITY VIOLATION!!!
session_start();

function session_count() {
  $filter = "sess_";
  $files = scandir(session_save_path());
  $count = 0;
  foreach ($files as $file) {
    if(strpos($file,$filter)===0) {
      $count += 1;
    }
  }
  return $count;
}

echo session_count();
?>
tom
Okay, this involves opening a huge security risk, so not the answer I'm looking for. Thanks though.
St. John Johnson