'PHP only Hit Counter?

So, I used to play with web development many years ago, and I'm a little rusty, but not THAT rusty!

I just made a full fledge video game page the other day using PHP variables to load different games into different size iframes. With that said, why on Earth can I not get a simple PHP hit counter to work? I have downloaded script after script after script, CHMOD'ed the txt file to 777, the whole 9. Does Chrome not support hit counters or something? It seems even the sites I visit that offer hit counters through them don't work on their demo pages!! What is the deal? I remember years ago, I copied about 10 very basic lines of code, saved it as a PHP file, uploaded it along with a blank txt file to a server, and bam, worked perfectly everytime. What has changed?

Here's the code I'm using. By the way. I tried adding this into my index.html, I also tried using it as a separate php file and calling on it with INCLUDE, everything. Nothing seems to work.

<?php

$open = fopen(“hits.txt”, “r+”);
$value = fgets($open);
$close = fclose($open);

$value++;

$open = fopen(“hits.txt”, “w+”);
fwrite($open, $value); // variable is not restated, bug fixed.
$close = fclose($open);

?>

and then where I want the results to be displayed, I have,

<?php echo $value; ?>

Any ideas?



Solution 1:[1]

You can use the following as a basic hit counter:

$counter = file_get_contents('./file') + 1;
file_put_contents('./file', $counter);

You may want to implement some way of checking that it's not just one user refreshing the page... Something simple like:

session_start();
if(empty($_SESSION['visited'])){
    $counter = file_get_contents('./file') + 1;
    file_put_contents('./file', $counter);
}

$_SESSION['visited'] = true;

Will check if the user has already visited the site in the same session and not increment the value if they have.

Solution 2:[2]

You can create an ajax file in PHP and call ajax in a time interval and display hit counter to page.

For this first of all create an ajax file: ajax_user_count.php

<?php
session_start();
$log_file_name = 'traffic_count.log';
$count = file_get_contents($log_file_name, true);
if(empty($count)){$count = 0;}  
if(isset($_POST['action'])){
    $action = $_POST['action'];
    if($action == 'enter'){
        if(!isset($_SESSION['user_count'])){
            $count += 1;
            if($count == 0) { $count = 1; }
            $_SESSION['user_count'] = $count;
            $message = $count; 
            file_put_contents($log_file_name, $message);        
        }
    } else if($action == 'leave'){
        $count -= 1;
        $_SESSION['user_count'] = $count;
        $message = $count; 
        file_put_contents($log_file_name, $message);
        session_destroy();  
    }
}

echo $count;
die;

Then call the ajax file by this

$(document).ready(function(){
    get_enter_web_traffic();
    setInterval(function(){ 
        get_enter_web_traffic();
    }, 1000);
    $(window).bind("beforeunload", function() {
        $.ajax({
                type: "POST",
                async: false,
                cache: false,
                url: "ajax_user_count.php",
                data: {'action' : 'leave'},
                success: function(result) { },
                error: function(data) { location.reload(); 
            }
        });
    });     

});

function get_enter_web_traffic(){
    var data = {'action' : 'enter'};    
    $.post('ajax_user_count.php',data,function(response){
        $('#count_user').html(response); // website hit count
    }); 
}

Solution 3:[3]

I am learning PHP currently. Came up with this easy to implement hit counter. Check it out

<?php 

$filename = "count.txt";// the text file to store count
// Open the file foe reading current count
$fp = fopen($filename, 'r');

//Get exiting count
$count = fread($fp, filesize($filename));

//close file
fclose($fp);

//Add 1 to the existing count
$count = $count +1;

//Display the number of hits
echo "<p>Total amount of Hits:" . $count. "</p>";

//Reopen to modify content
$fp = fopen($filename, 'w');

//write the new count to file
fwrite($fp, $count);

//close file
fclose($fp);

?>

Hope this piece of code comes in handy for someone.

Solution 4:[4]

file_put_contents('count.txt',"\n",FILE_APPEND|LOCK_EX);
$count = filesize("count.txt"); 

It appends one byte to a file and read the file size as the counter. it is the fastest and error free logic i found with 0.1 ms

Solution 5:[5]

This counts initial hits (not refreshes) and saves to a json file by date:

<?php

$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if (!$pageWasRefreshed) { #ignore page refresh
    $today = date("Y/m/d");
    $filename = 'traffic.json';
    $traffic = json_decode(file_get_contents($filename), true);
    $traffic[$today] += 1;
    file_put_contents($filename, json_encode($traffic));    
}

?>

The refresh checker is from PHP: Detect Page Refresh

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Subrata Mal
Solution 3 Jency
Solution 4 Abu Abdulla
Solution 5 ezChx