• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

PHP Counter recording time in a text file

I have the following code below and it records the ip address of the people visiting it and writes it into a text file but only does this if the ip address hasnt been before. i want to be able to record the time that the ip address was added to the text file. how do i do this?

<?php

$filename = "hits.txt" ;
$startdate = "November 2004" ;
$ip = getenv("REMOTE_ADDR") ;
$currentip = "$ip";
$file = file($filename);
$file = array_unique($file);
$date = date('m d, Y');


$file = "$filename";
$fd = fopen ($file, "r");
$fget= fread ($fd, filesize ($file));
fclose ($fd);
$totalips = htmlspecialchars($fget);
if (preg_match ("/$ip/i", "$totalips"))
{$file = file($filename);
$file = array_unique($file);
$hits = count($file);
$date = date('m d, Y');

echo "Visitors since,";
echo "$startdate: 000$hits";
?>
<br>
<?php

echo "$date";}

else
{
$fd = fopen ($filename , "r");
$fstring = fread ($fd , filesize ($filename)) ;
fclose($fd) ;
$fd = fopen ($filename , "w");
$fcounted = $fstring.$currentip."\n";
$fout= fwrite ($fd , $fcounted);
fclose($fd);
$file = file($filename);
$file = array_unique($file);
$hits = count($file);
$date = date('m d, Y');
echo "Visitors since,";
echo "$startdate: 000$hits";
echo "$date";
}

?>
0
aidanmcg34
Asked:
aidanmcg34
  • 10
  • 10
1 Solution
 
Diablo84Commented:
From the perspective of just writing every IP with date/time to the file all you need is:

$filename = "hits.txt" ;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y H:i:s");

$handle = fopen($filename,"a");
fwrite($handle,"$ip - $date\n");
fclose($handle);


This will write it as:

The IP - The Date and Time (eg: 127.0.0.1 - 27/11/04 14:31:30)

See the manual for changing the format of the date: http://us2.php.net/manual/en/function.date.php
0
 
aidanmcg34Author Commented:
yea thats what i want thanks but i only want it to record unique ip addresses
0
 
Diablo84Commented:
<?php
$filename = "hits.txt" ;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y H:i:s");

$contents = file($filename);
foreach ($contents as $var) {
 $parts = explode("-",$var);
 $ip_list[] = trim($parts[0]);
}
$ip_list = array_unique($ip_list);

if (!in_array($ip,$ip_list)) {
 $handle = fopen($filename,"a");
 fwrite($handle,"$ip - $date\n");
 fclose($handle);
}
?>

If you have the option of using a mysql database available to you i would give it some consideration as it will be much more efficient then using a text file.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Diablo84Commented:
At run time you shouldn't need this line:

$ip_list = array_unique($ip_list);

As the conditional will prevent duplicate IP's from being added without having to filter only unique IP's when you read the file. I added it for testing only.
0
 
aidanmcg34Author Commented:
I have the option of mysql but i dont have it on this computer and i need to get this coding done so it has to be done through text file for now.
how does the above code work cause i like to put plenty of comments in the script.
0
 
Diablo84Commented:
commented version:

 <?php
$filename = "hits.txt" ; //name of file
$ip = $_SERVER['REMOTE_ADDR']; //the ip address from the server super global array
$date = date("d/m/y H:i:s"); //formatted date using the date function

$contents = file($filename); //hits file loaded into an array (one line per array index)
foreach ($contents as $var) { //loops through each array item as $var (effectively loops through each line)
 $parts = explode("-",$var); //explodes each line into a temp array by - ($parts[0] will be "127.0.0.1 " parts[1] will be" 27/11/04 14:31:30"), this allows us to get rid of the date so get a unique list of IP's
 $ip_list[] = trim($parts[0]); //adds each ip to another array and trims off the white space
} //end loop

if (!in_array($ip,$ip_list)) { //a conditional that basically says if the users ip is not in the ip list then...
 $handle = fopen($filename,"a"); //open the file for writing with the pointer at the end of the file
 fwrite($handle,"$ip - $date\n"); //write the ip and date to the file (\n is new line so the next time it writes its on a new line not the same one)
 fclose($handle); //close the file
} //end conditional
?>
0
 
aidanmcg34Author Commented:
i want to put in a sentence into the web page that says the number of visitors that have been to the web page since the first date stored in the text file.
So far i have in
echo "There have been,";
echo "??,";
echo "visitors to this site since,";
echo " ?? ,":

but how do i get the number of unique ip addresses to be displayed and also the earliest date stored in the text file?
0
 
Diablo84Commented:
<?php
$filename = "hits.txt" ;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y H:i:s");

$contents = file($filename);
foreach ($contents as $var) {
 $parts = explode("-",$var);
 $ip_list[] = trim($parts[0]);
}

if (!in_array($ip,$ip_list)) {
 $ip_list[] = $ip;
 $handle = fopen($filename,"a");
 fwrite($handle,"$ip - $date\n");
 fclose($handle);
}

$start = explode("-",$contents[0]);
$start = trim($start[1]);

echo "There have been, ".count($ip_list)." visitors to this site since, $start";
?>
0
 
Diablo84Commented:
changes are:

$ip_list[] = $ip; //within the conditional, so the current users ip is added to the ip list as it wasn't included before

first entry is the first line of the file so we explode that line (the first array item from $contents) by - again:

$start = explode("-",$contents[0]);

Then trim it and assign the second index from the explode to the $start variable (which is the date part)

$start = trim($start[1]);
0
 
aidanmcg34Author Commented:
have 2 go for an hour or so but thanks.
0
 
aidanmcg34Author Commented:
i want to print out a few lines on the web page that say how many people have visited the site in the last week and the last month. and possibly the number of hits every week.
how would this be done?
0
 
Diablo84Commented:
Doing things like this with a text file is going to put stress on your server, particularily as the ip log grows in size, it could dramatically slow down the loading time on your page.

I will show you an example of how you could handle visits from the last month but anything else is going to require more processing and will result in a slow script.

<?php
$filename = "hits.txt" ;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y H:i:s");
$visits_month = 0;

$contents = file($filename);
foreach ($contents as $var) {
 $parts = explode("-",$var);
 $ip_list[] = trim($parts[0]);
 $date = explode("/",trim($parts[1]));
 if (date("m") == $date[1]) $visits_month++;
}

if (!in_array($ip,$ip_list)) {
 $ip_list[] = $ip;
 $handle = fopen($filename,"a");
 fwrite($handle,"$ip - $date\n");
 fclose($handle);
}

$start = explode("-",$contents[0]);
$start = trim($start[1]);

echo "There have been, ".count($ip_list)." visitors to this site since, $start and $visits_month visits this month";
?>
0
 
aidanmcg34Author Commented:
what does the two lines do?

$date = explode("/",trim($parts[1]));
 if (date("m") == $date[1]) $visits_month++;
0
 
aidanmcg34Author Commented:
oh yea and im only doing this script to learn how to do stuff so the numper of ips is always goin to be small so i dont have to worry about slowing the server down.
0
 
aidanmcg34Author Commented:
another thing i just noticed in the file hits.txt there are four ip addresses the first 3 have date and times beside them but the fourth just says array beside it. why is this?
0
 
Diablo84Commented:
Human Error on my part, two variables sharing the same name, just change the piece just added:

 $date = explode("/",trim($parts[1]));
 if (date("m") == $date[1]) $visits_month++;

to:

 $tempdate = explode("/",trim($parts[1]));
 if (date("m") == $tempdate[1]) $visits_month++;

And to explain these two lines:

//here we are breaking up the array item that contains the date by "\" so now we have a temp array:
// $tempdate[0] is the day  $tempdate[1] is the month and  $tempdate[2] is the rest of it
 $tempdate = explode("/",trim($parts[1]));

//at the moment we only need the motth so if $tempdate[1] equals the current month as we
//loop through the array of ip's increment the monthly visits by one
 if (date("m") == $tempdate[1]) $visits_month++;


Getting the hits for the last week is feasible but requires more coding.

I can provide you with an example of that but first, how important is the date being stored in the file? If you are only using it for the purposes of calculating recent hits it would be easier to store it as a unix timestamp (eg. 1101600265) from the perspective of processing, much easier.

As for calculating hits for every week, that will require a more lengthy script that i'm afraid i simply don't have the time to write.
0
 
aidanmcg34Author Commented:
the format of the date doesnt matter i was originally considering using the timestamp but someone else suggested just a date and hours mins seconds . i only store the date so i can produce results on the screen sayin how many people have visited the site since a certain date and i just wanted to present some statistics didnt necessarily have to be visitors in last month week etc so if youd any suggestions it would be greatly appreciated.

Thanks for your help.
0
 
Diablo84Commented:
ok, working with a timestamp gets rid of a big headache because it means you already have the data you need in a usable format without having to break the date apart and effectively extracting the required parts. With this im mind i am also going to make a minor adjustment to the way the data is stored to make it more usable.

The following example displays data for the overall, last month and last week (NOTE!! delete the contents of the hits file before running this otherwise it wont be compatible with the following and will error):

<?php
$filename = "hits.txt" ;
$ip = $_SERVER['REMOTE_ADDR'];
$visits_month = 0;
$visits_week = 0;

$contents = file($filename);
foreach ($contents as $var) {
 $parts = explode("|",$var);
 $ip_list[] = $parts[0];
 if (date("m") == date("m",$parts[1])) {
  $visits_month++;
  if (date("W") == date("W",$parts[1])) $visits_week++;
 }
}

if (!in_array($ip,$ip_list)) {
 $ip_list[] = $ip;
 $handle = fopen($filename,"a");
 fwrite($handle,$ip."|".time()."\n");
 fclose($handle);
}

$start = explode("|",$contents[0]);
$start = date("d/m/Y H:i:s",$start[1]);

echo "There have been, ".count($ip_list)." visitors to this site since, $start with $visits_month visits this month and $visits_week visits this week";
?>

I will comment it tomorrow if needed, and give you some pointers towards expanding its functionality.

Best Wishes.
0
 
aidanmcg34Author Commented:
could you add the comments to this please and ill just click the accept thing to give ya the points.
thanks for all your help
0
 
Diablo84Commented:
sure :)

<?php
$filename = "hits.txt" ; //name of hits file
$ip = $_SERVER['REMOTE_ADDR']; //users ip
$visits_month = 0; //set the hits for the last month as an initial 0
$visits_week = 0; //set the hits for the last week as an initial 0

$contents = file($filename); //load the hits file into an array, 1 line per array item
foreach ($contents as $var) { //loop through each line as $var
 $parts = explode("|",$var); //break up each line by | $parts[0] = the ip $parts[1] = the timestamp
 $ip_list[] = $parts[0]; //add the ip to the ip list array
 if (date("m") == date("m",$parts[1])) { //if the current month is the same as the month for the timestamp then..
  $visits_month++; //increment the last month visits count by 1
  if (date("W") == date("W",$parts[1])) $visits_week++; //if the current week number matches the timestamps week number increment the last week visits count by 1
 } //end month conditional
} //end loop

if (!in_array($ip,$ip_list)) { //if the users current ip isnt in the ip list (which is built from the ips in the file) then
 $ip_list[] = $ip; //add their ip to the list array
 $handle = fopen($filename,"a"); //open the file for writing
 fwrite($handle,$ip."|".time()."\n"); //write the ip and timestamp to the file
 fclose($handle); //close the file
} //end if check

$start = explode("|",$contents[0]); //break the first line of the file up by |
$start = date("d/m/Y H:i:s",$start[1]); //format the timestamp from the first line with the date function, this is the earliest hit date

//output the variables, count($ip_list) just counts the number of items in the array which is your number of total hits
echo "There have been, ".count($ip_list)." visitors to this site since, $start with $visits_month visits this month and $visits_week visits this week";
?>

and no problem.

|)iablo
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 10
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now