Printable Version of Topic

Click here to view this topic in its original format

Forums _ Webmasters' Corner _ PHP Online Users

Posted by: Mikeplyts Aug 15 2010, 05:41 PM

So, it took me a while, but I think I managed to come close to a PHP script that displays how many visitors are online at once. However, I have a bit of a problem. It doesn't necessarily work. Let me show you the function first.

This is my little function, online():

CODE
function online() {
$root = realpath($_SERVER['DOCUMENT_ROOT']);
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$users = array();
$online = array();
$file = $root . '/includes/template/online.txt';
$session = 25;

if (!file_exists($file)) {
$handle = fopen($file, 'w+');
fclose($handle);
}

$handle = fopen($file, 'r');
flock($handle, LOCK_SH);
while (!feof($file)) {
$users[] = rtrim(fgets($handle, 32));
}
flock($handle, LOCK_UN);
fclose($handle);

$x = 0;
$y = false;
foreach ($users as $key => $data) {
list( , $z) = explode('|', $data);
if ($time - $z >= $session * 60) {
$users[$x] = '';
}
else {
if (strpos($data, $ip) !== false) {
$y = true;
$users[$x] = $ip . '|' . $time;
}
}
$x++;
}

if ($y == false) {
$users[] = $ip . '|' . $time;
}

$handle = fopen($file, 'w+');
flock($handle, LOCK_EX);
$i = 0;
foreach ($users as $single) {
if ($single != '') {
fwrite($handle, $single . '\r\n');
$i++;
}
}
flock($handle, LOCK_UN);
fclose($handle);

if ($a != true) {
echo $i . 'online';
}
}

Everything looks great but I get a little warning.
CODE
Warning: feof(): supplied argument is not a valid stream resource


I'm thinking it's the path ($file) but I don't know what to put there. Any thoughts?

Posted by: mipadi Aug 15 2010, 11:44 PM

Pass the file handle ($handle) to feof().

Posted by: Mikeplyts Aug 16 2010, 06:13 AM

*sigh* I hate not noticing such simple things.

Anyway, yeah. Thanks.