PHP filesize reporting old size
Asked Answered
A

3

29

The following code is part of a PHP web-service I've written. It takes some uploaded Base64 data, decodes it, and appends it to a file. This all works fine.

The problem is that when I read the file size after the append operation I get the size the file was before the append operation.

$fileOut = fopen($filepath.$filename, "ab")
fwrite($fileOut, base64_decode($data));
fflush($fileOut);
fclose($fileOut);

$newSize = filesize($filepath.$filename);   // gives old file size

What am I doing wrong?

System is:

  • PHP 5.2.14
  • Apache 2.2.16
  • Linux kernel 2.6.18
Albers answered 20/9, 2010 at 0:6 Comment(1)
b is used for outputting binary data. It shouldn't cause the issue.Kafir
M
47

On Linux based systems, data fetched by filesize() is "statcached".

Try calling clearstatcache(); before the filesize call.

Must answered 20/9, 2010 at 0:12 Comment(0)
K
12

According to the PHP manual:

The results of this function are cached. See clearstatcache() for more details.

https://www.php.net/manual/en/function.filesize.php

Basically, you have to clear the stat cache after the file operation:

$fileOut = fopen($filepath.$filename, "ab")
fwrite($fileOut, base64_decode($data));
fflush($fileOut);
fclose($fileOut);

clearstatcache();

$newSize = filesize($filepath.$filename);
Kafir answered 20/9, 2010 at 0:12 Comment(0)
I
4

PHP stores all file metadata it reads in a cache, so it's likely that the file size is already stored in that cache, and you need to clear it. See clearstatcache and call it before you call filesize.

Interfuse answered 20/9, 2010 at 0:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.