I’m trying to make a download counter in a website for a video game in PHP, but for some reason, instead of incrementing the contents of the downloadcount.txt file by 1, it takes the number, increments it, and appends it to the end of the file. How could I just make it replace the file contents instead of appending it?
Here’s the source:
<?php
ob_start();
$newURL = 'versions/v1.0.0aplha/Dungeon1UP.zip';
//header('Location: '.$newURL);
//increment download counter
$file = fopen("downloadcount.txt", "w+") or die("Unable to open file!");
$content = fread($file,filesize("downloadcount.txt"));
echo $content;
$output = (int) $content + 1;
//$output = 'test';
fwrite($file, $output);
fclose($file);
ob_end_flush();
?>
The number in the file is supposed to increase by one every time, but instead, it gives me numbers like this: 101110121011101310111012101110149.2233720368548E+189.2233720368548E+189.2233720368548E+18
4
Answers
It will be much simpler to use
file_get_contents
/file_put_contents
:You can get the content, check if the file has data. If not initialise to 0 and then just replace the content.
Check
$str
or directly content inside the fileThat appending should just be a typecasting problem, but I would not encourage you to handle counts the file way. In order to count the number of downloads for a file, it’s better to make a database update of a row using transactions to handle concurrency properly, as doing it the file way could compromise accuracy.
As correctly pointed out in one of the comments, for your specific case you can use fseek ( $file, 0 ) right before writing, such as:
Or even simpler you can rewind($file) before writing, this will ensure that the next write happens at byte 0 – ie the start of the file.
The reason why the file gets appended it is because you’re opening the file in append and truncate mode, that is “w+”. You have to open it in readwrite mode in case you do not want to reset the contents, just “r+” on your fopen, such as:
Just make sure the file exists before writing!
Please see fopen modes here:
https://www.php.net/manual/en/function.fopen.php
And working code here:
https://bpaste.net/show/iasj