SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Apr 2001
    Location
    Michigan
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simple PHP Counter

    I'm trying to make a simple php script for my site that writes the number of vistors i've had to a text file called hits.txt. Below is the code for counter.php.
    PHP Code:
    <?php
    $fp 
    fopen ("hits.txt""w+");
    while (!
    feof ($fp)) {
    $line fgets($fp4096);
    }
    $line++;
    fwrite($fp$line);
    echo(
    $line);
    ?>
    When I run the file it just deletes the old value, but doesn't write the new one. Any help would be appreciated. Thanks.

  2. #2
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I could never get the w+ to work right, I am probably doing something wrong, but I did get this code to work.

    PHP Code:
    <?
    $in 
    fopen ("hits.txt""r");
    while (!
    feof($in)) {
        
    $line fgets($in1024);
        }
    fclose($in);

    $line++;
    echo(
    $line);

    $out fopen ("hits.txt""w");
    fwrite($out$line);
    fclose($out);

    ?>
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  3. #3
    SitePoint Member
    Join Date
    Apr 2001
    Location
    Newcastle, UK
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    of course if the counter is just going to be in its own file you can go all fancy and just store the number in the script file itself with something like:

    PHP Code:
    <?
    $hits
    =0;

    $hits++;
    echo 
    $hits;
    $filename=basename($PHP_SELF);
    $file=fopen("$filename","r+");
    fputs("<?\n\$hits=$hits\n",$file);
    fclose($file);

    ?>
    and yes, I know its pretty similar to the one in the web application development, but theres only so many ways to write something. I would note tho, if you use that code as an include you'd be best changnig $filename to equal the absolute url to the counter file, otherwise you'll start rewriting the file you included from


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •