I'm programming a visitcounter for my website...
The textfile should look like this:
- index.php: 4 views
- contact.php: 6
- views etc.
Here is my code:
function set_cookie(){
setcookie("counter", "Don't delete this cookie!", time()+600);
}
function count_views(){
$page = basename($_SERVER['PHP_SELF']);
$file = fopen("counter.txt","r+");
$page_found = false;
if (!isset($_COOKIE['counter'])) {
while (!feof($file)) {
$currentline = fgets($file);
if(strpos($currentline, ":")){
$filecounter = explode(":", $currentline);
$pif = $filecounter[0]; $counterstand = $filecounter[1];
if ($pif == $page) {
$counterstand = intval($counterstand);
$counterstand++;
fseek($file, -1);
fwrite($file, $counterstand);
$page_found = true;
set_cookie();
}
}
}
if (!$page_found) { fwrite($file, $page . ": 1\n"); }
fclose($file);
}
}
And now my problem: Everytime i visit the page he is not able to update the new value. so at the end it looks like this
- home.php: 1
- index.php: 1
- 2222
It looks like he takes the 1
from the correct line after the filename, and prints it at the end of the file...
how can I write the new value in the correct line?