The problem is that you're doing multiple filesize()
calls. After you do the first one the size is cached. You then write to the file and then do filesize()
on it again and filesize()
is returning what it returned last time even though the file size has changed since the last time it ran (due to PKCS padding). A demo:
<?php
file_put_contents('demo.txt', 'zzz');
echo filesize('demo.txt') . "\r\n";
file_put_contents('demo.txt', 'zzzzzz');
echo filesize('demo.txt');
You'd probably expect that to return 3 and 6 wouldn't you? For me it returns 3 and 3.
I'd recommend using file_get_contents() and file_put_contents(). If you must use fopen and fgets then do clearstatcache() as well after each filesize()
call.