1

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?

Makoto
  • 104,088
  • 27
  • 192
  • 230
JJinVA
  • 51
  • 1
  • 2
  • 6
  • 4
    Rename the index.html to index.php. The server side code might not get parsed when contained in .html files... – ppeterka Sep 23 '13 at 12:47
  • 3
    `"I have downloaded script after script after script"` - But have you written or understood any of the code? In what way does it not work as expected? If the end result isn't what you expect, do some debugging. Is the code running at all? What are the runtime values? At what point does the observed behavior deviate from the expected behavior? – David Sep 23 '13 at 12:48
  • There is something wrong with the double quotes: it should be `"` instead of `”`. – Willem Van Onsem Sep 23 '13 at 12:51
  • I figured out what the problem was. I had to save index.html as index.php. Apparently, it has to be within a PHP file inorder to work. – JJinVA Sep 23 '13 at 13:19
  • This is not a good example of a question since it includes one paragraph of pure ranting, no clear error description. "Nothing seems to work." Is the file created? Do you get an error message? Do you see anything in the webserver logs? Have you tried reducing the code to check if it is even called? – Sybille Peters Dec 11 '22 at 09:31
  • I think more helpful would have been here a question (and answers) how to troubleshoot these kind of things. – Sybille Peters Dec 11 '22 at 09:32

5 Answers5

9

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.

Steven
  • 6,053
  • 2
  • 16
  • 28
  • What happens if two users load the page at the exact same time? – Thoracius Appotite Dec 29 '20 at 02:42
  • 1
    @ThoraciusAppotite Pretty much nothing; the whole operation should take less than `2 milliseconds`. So the likelihood of that happening at exactly the same time is almost `0%`. If two people new users were to manage to hit the page within a fraction of a millisecond of each other then the worst case scenario would be that they'd read the same number from the file (e.g. `100`) increment it and write it back. I.e. they'd both write back `101` when you would expect the counter to be `102`. – Steven Dec 29 '20 at 13:28
  • @ThoraciusAppotite Almost insignificantly low chance of that happening though; the only real way around it would be to store visits in a database and `COUNT` the visits... – Steven Dec 29 '20 at 13:29
  • In most cases a hit counter is just for fun, but were accuracy paramount (e.g. "1 millionth visitor gets a prize") one could implement file locking. – Thoracius Appotite Dec 29 '20 at 21:21
  • 1
    @ThoraciusAppotite That would indeed be one way around it. However, in a situation where I'd expect multiple hits in a millisecond I'm not sure I'd want to be hanging the server with file locks? A database is definitely the way I'd go (especially with your example -- as that way any questions regarding accuracy can be verified with data) – Steven Dec 29 '20 at 22:20
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
    }); 
}
Subrata Mal
  • 91
  • 1
  • 2
1

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.

Jency
  • 269
  • 1
  • 13
1

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

ezChx
  • 4,024
  • 1
  • 19
  • 16
0
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