A simple counter in PhP

Discussion in 'PHP' started by Nikolas, Nov 10, 2005.

  1. #1
    Here is the code for a very simple counter that you can add to your site :

    <?php
    if(file_exists("hits.txt"))
    {
        $hits = file_get_contents("hits.txt");
    }else{
        $hits=0;
    }
    $hits++;
    
    $ha = fopen("hits.txt", "w");
    fwrite($ha, $hits);
    fclose($ha);
    ?>
    PHP:
    You can add it to the .php page that you want to count, plus you can add this code if you want it to be visible :

    
    <?php
    echo $hits." visitors";
    ?>
    
    PHP:
     
    Nikolas, Nov 10, 2005 IP
  2. dataman

    dataman Peon

    Messages:
    94
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    But if your writing you should be locking...

    I think it would also be better to use single IO handle than to use (2). This ways you open, update then close.

    jb
     
    dataman, Nov 10, 2005 IP
  3. today

    today Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Or better use free hit counter :) There is a lot of at web
     
    today, Nov 10, 2005 IP
  4. fsmedia

    fsmedia Prominent Member

    Messages:
    5,163
    Likes Received:
    262
    Best Answers:
    0
    Trophy Points:
    390
    #4
    Better yet, don't use a counter at all, they're so the 90s =P
     
    fsmedia, Nov 10, 2005 IP
  5. hnn

    hnn Peon

    Messages:
    91
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    If you want a counter, use an DB instead. Filesystems is slow with reading and writing...
     
    hnn, Nov 11, 2005 IP