php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72930 filesize bug after rewrite.
Submitted: 2016-08-23 10:36 UTC Modified: 2016-08-23 15:38 UTC
From: frank123m at gmail dot com Assigned: cmb (profile)
Status: Not a bug Package: Filesystem function related
PHP Version: 5.6.25 OS: ubuntu
Private report: No CVE-ID: None
 [2016-08-23 10:36 UTC] frank123m at gmail dot com
Description:
------------
function hit_count() {

  $filename = 'count.txt';

  $handle = fopen($filename, 'r');
  $current = fread($handle, filesize($filename));
  fclose($handle);
  
  $current_inc = $current + 1;
  
  $handle = fopen($filename, 'w');
  fwrite($handle, $current_inc);
  fclose($handle);
  
  $handle = fopen($filename, 'r');
  $current = fread($handle, filesize($filename));
  fclose($handle);
  
  echo $current;

}

Test script:
---------------
count.txt:
example: 99->100
echo $current will show 10 instead of 100.

filesize($filename) remain the same after fwrite. its the bug.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-08-23 10:53 UTC] cmb@php.net
-Status: Open +Status: Not a bug -Assigned To: +Assigned To: cmb
 [2016-08-23 10:53 UTC] cmb@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

The bug is rather in your script. You're reading the file size,
and writing this (increased by one) back to the file. Then you
expect the file size to have increased.
 [2016-08-23 12:26 UTC] frank123m at gmail dot com
hello, did you notice I use the filesize twice? (before write and after)
I didn't store it in a variable.
it should be read the new filesize, so I thought it is a bug that still use the old one.
 [2016-08-23 12:43 UTC] frank123m at gmail dot com
well, thanks.
the answer is the filesize function need clearstatcache() to clear its cache.
then it can be used again.
 [2016-08-23 15:10 UTC] requinix@php.net
-Package: Math related +Package: Filesystem function related
 [2016-08-23 15:10 UTC] requinix@php.net
Even better would be to not bother with fopen/read/write/close and to use file_get|put_contents instead. It's why they exist.
Better still would be to not use files to store highly mutable data, because if you don't do it right then your code will start failing with enough concurrency.
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Sun Nov 29 02:01:23 2020 UTC