Richard
Richard

Reputation: 7433

filesize() of a file doesn't show the actual file size

I have the following code:

<?php
    for ($i = 0; $i < 6; $i++) {
        $file = fopen( 'dummy.txt', 'a' );
        echo filesize('dummy.txt') . "<br>";
        fwrite($file, "b\n");
        echo filesize('dummy.txt') . "<br>";
        fclose($file);
    }
?>

And it yields:

0
0
0
0
0
0
0
0
0
0
0
0

However, when I open my dummy.txt file, it shows that I have successfully written the letters I want. I don't understand how filesize() can show a file with size 0 when I clearly write to the text file per iteration and then closing said file. Could someone please enlighten me?

Upvotes: 0

Views: 129

Answers (1)

neophytte
neophytte

Reputation: 690

You are looking at an open file, you need to close the file and clear the cache by insert a call to clearstatcache() before calling filesize()

Manual page for filesize: http://php.net/manual/en/function.filesize.php

Code should read:

<?php
    for ($i = 0; $i < 6; $i++) {
        $file = fopen( 'dummy.txt', 'a' );
        fwrite($file, "b\n");
        fclose($file);
        clearstatcache();
        echo filesize('dummy.txt') . "<br>";
    }
?>

Upvotes: 2

Related Questions