I am re-posting this question since I did not get any useful answers the first time.
I have a simple session counter on my site utilizing session_save_path(). The code does not work in a shared hosting environment because it returns a count of all sessions on the server for all sites – or so I presume.
Could someone tell me how I can modify this so it works properly. I know counting sessions does not accurately reflect the numbers but it does not have to be a 100% accurate. I also do not think that hitting the database is a smart idea for a simple function like this.
There has got to be a way to implement this the right way. Can you help?
Thank you!
<?php
//------------------------------------------------------------
// VISITORS ONLINE COUNTER
//------------------------------------------------------------
if (!isset($_SESSION)) {
session_start();
}
function visitorsOnline()
{
$session_path = session_save_path();
$visitors = 0;
$handle = opendir($session_path);
while(( $file = readdir($handle) ) != false)
{
if($file != "." && $file != "..")
{
if(preg_match('/^sess/', $file))
{
$visitors++;
}
}
}
return $visitors;
}
?>
You might be able to tell “your” session files apart from those of other users using
fileowner()oris_readable()– the latter following the logic that you will have only access to your session files (well, hopefully!)This will heavily depend on the server configuration, if it works at all.
The only really good way that comes to my mind is to have your scripts write into a separate database table for each session, frequently clean up old records, get the count from there.