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.