Filebase
Filebase copied to clipboard
Use clearstatcache to avoid wrong filesize
I was doing some tests and when I tried manipulate a document more than one time, I got an encoding error. Investigating the error, I saw that the function Filesystem::read()
use fread()
function to read the document content. And is passed the size of the length of the buffer with the function filesize
. What happens is that PHP uses a cache to save the file status and this behavior can affect the value of filesize
function.
When I add clearstatcache()
on Filesystem::read()
before the fread($file, filesize($path))
, the error doesn't happen anymore.
I tried isolate in a script to prove what is happen on my case, but it just happen on my application. So I create a script that use the PHP library functions used on this project to simulate the error.
function test_filesize($path, $contents, $clearstatcache) {
$fp = fopen($path, 'w+');
if(!flock($fp, LOCK_EX))
{
return false;
}
$result = fwrite($fp, $contents);
flock($fp, LOCK_UN);
fclose($fp);
if($clearstatcache) {
clearstatcache();
}
$file = fopen($path, 'r');
$filesize = filesize($path);
fclose($file);
echo sprintf('Filesize expected: %d, got: %d', strlen($contents), $filesize) . PHP_EOL;
}
$path = 'some-file-path';
echo 'Not using clearstatcache' . PHP_EOL;
test_filesize( $path, 'a', false);
test_filesize( $path, 'aa', false);
test_filesize( $path, 'aaa', false);
echo 'Using clearstatcache' . PHP_EOL;
test_filesize( $path, 'a', true);
test_filesize( $path, 'aa', true);
test_filesize( $path, 'aaa', true);
This script outputs:
Not using clearstatcache
Filesize expected: 1, got: 1
Filesize expected: 2, got: 1
Filesize expected: 3, got: 1
Using clearstatcache
Filesize expected: 1, got: 1
Filesize expected: 2, got: 2
Filesize expected: 3, got: 3