php counter, file writing problem.
Posted: Mon Jul 18, 2005 6:17 am
Hi everyone. I'm new to PHP and was trying to implement a simple pageviews counter that increments pageviews if last IP that visited the page is different from current IP. (sorry for my bad english, I hope you got the idea).
I thought I had to use a file to store pageviews and last IP.
My code partially works. at the first visit the txt file is created and looks like this:
1
82.50.blah.blah
at the second pageviews the counter file looks like this
1
82.47.blah.blah
where's that more line coming from? here's the code.
Hope someone will be so kind to help. It's like 2 days I'm working on this and it's driving me crazy 
Thanks in advance.
Gabriele.
I thought I had to use a file to store pageviews and last IP.
My code partially works. at the first visit the txt file is created and looks like this:
1
82.50.blah.blah
at the second pageviews the counter file looks like this
1
82.47.blah.blah
where's that more line coming from? here's the code.
Code: Select all
$filename = 'contatore.txt';
$user_ip = getenv("REMOTE_ADDR");
//if file exists
if (file_exists($filename)) {
$fp = fopen ($filename , 'r');
$cnt = fgets ($fp , 1024);
$last_ip = fgets($fp , 1024);
fclose($fp);
print ("page viewed $cnt times. your IP is $user_ip");
if ( $last_ip != $user_ip ) {
$fp = fopen ($filename , 'w');
$cnt++;
fwrite($fp , $cnt);
fwrite($fp , "\n");
fwrite($fp , $user_ip);
fclose($fp); }
}
//if file doesn't exist, create it and set views to 1.
else {
$fp = fopen ($filename , 'w');
$cnt=1;
fwrite($fp , $cnt);
fwrite($fp , "\n");
fwrite($fp , $user_ip);
fclose($fp);
print ("page viewed $cnt times. your IP is $user_ip");
}Thanks in advance.
Gabriele.