Jump to content

Counter not working properly


AliceAmphetamine

Recommended Posts

I have a small file that I have included on my pages to keep track of how many visits a given page received and saves them each to an individual .txt file. If the .txt file for a given page does not exist it will create a .txt file for it.

 

Program is that it is not increasing the the count in the .txt files if they do exist. I am still pretty new to php so I am having trouble figuring out where I went wrong, I've spent about an hour and a half now trying to figure out a solution but now I am resorting to a second pair of eyes to help assist me.

 

here is what I currently have.

 

<?php
$pageid = $_GET["id"];
if ( $pageid == "" ) {
header( 'Location: index.php?id=home' ) ;
}
else{
if (is_file($pageid.txt)) {
$count = ("stats/$pageid.txt");
$hits = file($count);
$hits[0] + 1;
$fp = fopen($count , "w");
fputs($fp , "$hits[0]");
fclose($fp);
} else {
$myFile = "stats/$pageid.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "1";
fwrite($fh, $stringData);
fclose($fh);
}
}
?>

 

Thank you in advance for any and all suggestions and assistance that is provided.

Link to comment
https://forums.phpfreaks.com/topic/188525-counter-not-working-properly/
Share on other sites

Try this instead

$pageid = isset($_GET['id']) ? $_GET["id"] : '';
if ($pageid == '') {
header('Location: index.php?id=home');
die();
} else {
    $filename = "stats/$pageid.txt";
    if(file_exists($filename)) {
        $count = file_get_contents($filename);
        file_put_contents($filename, ++$count);
    }else{
        file_put_contents($filename, 1);
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.