Designer? Programmer? Enthusiast? Join Open Designs Now!

Open Designs Forum » General Talk

PHP click-counter help

(3 posts)
  • Started 2 years ago by willwood
  • Latest reply from willwood
  1. willwood
    Member

    Hi,
    I will admit that I know little about PHP. I have been trying to implement a very basic click counter on a website which displays how many times a file has been downloaded. I searched the internet and found a very basic one which stores click tallies in a plain text file instead of an SQL database. The code I've got is as follows:


    <?php
    if(!file_exists('counters/file1.txt')){
    file_put_contents('counters/file1.txt', '0');
    }
    if($_GET['click'] == 'yes'){
    file_put_contents('counters/file1.txt', ((int) file_get_contents('counters/file1.txt')) + 1);
    header('Location: ' . $_SERVER['SCRIPT_NAME']);
    die;
    }
    ?>
    <h1><?php echo file_get_contents('counters/file1.txt'); ?></h1>
    clickMe

    The page loads fine and the download number is displayed correctly above the link. But when the download link is clicked and the file begins downloading, an error is displayed:

    Warning: Cannot modify header information - headers already sent by (output started at /Users/Will/Sites/code.php:79) in /Users/Will/Sites/code.php on line 85

    Incidentally line 85 of the code is: header('Location: ' . $_SERVER['SCRIPT_NAME']);

    If a user hits the back button, they are returned back to the page and the download click counter value has updated. So the code I'm using above is partly working, except for this error when the download link is clicked. Did some more reading on the internet and some suggestions were to remove line breaks from the code which I did. But this did not fix the problem. I have tried putting the PHP code in the head section of a page and also tried it in the body section immediately above the download link (like in the code above). Same error message though where ever I put the code.

    Can anyone see anything wrong with this code? I'm getting the same error when I test the site locally on my computer and when I upload a test page to my web server.

    Posted 2 years ago #
  2. greg
    Member

    Headers must be sent before anything is displayed on your page, so what's happening is something is being displayed and then more headers are being sent which doesn't work, hence the error. It's a little difficult to diagnose without seeing your complete code, but I'd guess whatever is at line 79 is causing the error. Move that line somewhere below line 85 and it should stop complaining.

    Posted 2 years ago #
  3. willwood
    Member

    Thanks Greg.
    I tried moving the code around a bit but it didn't work or it broke the counter. So then I moved everything between the <?php and ?> tags to above the DOCTYPE in my page. That worked fine and gave no errors.

    Posted 2 years ago #

RSS feed for this topic