Hello! I’m trying to make an active users script in PHP, not because I need one, because I want to know if i can. I made one that worked with PHP sessions but then it failed to work with people who had cookies turned off. So, now the script i’m using stored the time and users IP in a flat file. Needless to say it doesn’t work for a seemingly unknown reason.
It’s a pretty small script that I heavily commented so I wouldn’t get lost. If one of you more experienced PHP gurus can take a look through it real fast and tell me what’s wrong and what I could do to fix it that’d be great.
<?php
// open file for reading and writing
$handle = fopen("test.txt", "a+");
// if you can read the file (IE if it's not empty)
if($contents = fread($handle, filesize("test.txt"))){
// split the different times and IP's
$times = split(',', $contents);
// take off last array string because it's blank
array_pop($times);
$none = 0;
// loop through times and ip's
foreach($times as $time){
// split times from IP's
$split = split('-', $time);
$time = $split[0];
$ip = $split[1];
// if users IP is in the contents record it
if($ip == $_SERVER['REMOTE_ADDR']){
$none = 1;
}
}
// if the users IP did not exist in the file.
if($none != 1){
// write the IP address and time
if(fwrite($handle, time().'-'. $_SERVER['REMOTE_ADDR'].',') == FALSE){
echo "failed to write part one";}
else{
echo "wrote: ". time().'-'. $_SERVER['REMOTE_ADDR'].',';}
}
}
// if we cannot open the file, write the IP address and time
else{fwrite($handle, time().'-'. $_SERVER['REMOTE_ADDR'].',');}
fclose($handle);
// open file
$handle = fopen("test.txt", "r+");
// if we can open the file
if($contents = fread($handle, filesize("test.txt"))){
// split the different times and IP's
$times = split(',', $contents);
// get rid of last string
array_pop($times);
// loop through times and IPs
foreach($times as $time){
// split times from IP's
$ip = split('-', $time);
$time = $ip[0];
$ip = $ip[1];
// if the time in the file is still good add it to an array
if($time + 10 < time()){
$activeusers .= $time.'-'.$ip.',';
echo "Time good, added user";}
// if the time isn't still good but the users IP
// exists in the file add them to active uers but use current time
elseif($ip == $_SERVER['REMOTE_ADDR']){
$activeusers .= time().'-'.$ip.',';
echo "Time expired, but added user";}
}
if(fwrite($handle, $activeusers) == FALSE){
echo "<br>failed to write part two<br>";}
}
else{echo "Failed to open file for writing second part";}
echo "<br>";
echo $activeusers;
I’ve rewritten this script twice and each time it’s had a different problem.