Filesize () always reads 0 bytes, even if the file size is not 0 bytes

I wrote the code below, at the moment I am testing, so there are no database queries in the code.

The code below, where he says if(filesize($filename) != 0), always goes to else, although the file is not 0 bytes and contains 16 bytes of data. I get nothing, it always seems that the file is 0 bytes.

It seems to me that it is easier for me to show my code (there may be other errors, but I check each error when I deal with them, one at a time). I am not getting any PHP errors or anything else.

$filename = 'memberlist.txt';
$file_directory = dirname($filename);
$fopen = fopen($filename, 'w+');

// check is file exists and is writable
if(file_exists($filename) && is_writable($file_directory)){

    // clear statcache else filesize could be incorrect
    clearstatcache();

    // for testing, shows 0 bytes even though file is 16 bytes
    // file has inside without quotes:   '1487071595 ; 582'
    echo "The file size is actually ".filesize($filename)." bytes.\n";

    // check if file contains any data, also tried !==
    // always goes to else even though not 0 bytes in size
    if(filesize($filename) != 0){

        // read file into an array
        $fread = file($filename);

        // get current time
        $current_time = time();

        foreach($fread as $read){
            $var   = explode(';', $read);
            $oldtime  = $var[0];
            $member_count = $var[1];
        }
            if($current_time - $oldtime >= 86400){
                // 24 hours or more so we query db and write new member count to file
                echo 'more than 24 hours has passed'; // for testing

            } else {
                // less than 24 hours so don't query db just read member count from file
                echo 'less than 24 hours has passed'; // for testing
            }
    } else { // WE ALWAYS END UP HERE
        // else file is empty so we add data
        $current_time = time().' ; ';
        $member_count = 582; // this value will come from a database
        fwrite($fopen, $current_time.$member_count);
        fclose($fopen);
        //echo "The file is empty so write new data to file. File size is actually ".filesize($filename)." bytes.\n"; 
    }

} else {
    // file either does not exist or cant be written to
    echo 'file does not exist or is not writeable'; // for testing
}

, , . script , 24 , member_count else, 24 , , - , .

1:

:

echo "The file size is actually ".filesize($filename)." bytes.\n";

, 0 .

0 .

var_dump (filesize($filename));

:

Int (0)

+4
1

:

fopen($filename, "w+") 

w+ :

; . , .

, 0.

, r+

+8

Source: https://habr.com/ru/post/1669694/


All Articles