PHP / Apache fwrite updates the modified date but doesn't write

Viewed 75

Using PHP fwrite simple example, the code updates the file (Modified date/time changes) but nothing is written. I get no errors. I get:

Success, wrote (Add this to the file ) to file (./errors/test.txt)

Yet the file is empty and the date modifies changes - as though it was written to.

I'm on PHP 7.0/Apache2 Debian (Raspberry Pi B). I started setting the file permissions to 755 and changed it to 777 with no success. Owner is www-data - and I've tried root and another owner - both fail, because you need to set owner to www-data for it to write.

I have tried both ./errors/test.txt and errors/test.txt - it makes no difference.

I have tried fopen($filename, 'a') and fopen($filename, 'w') and both produce the same result.

<?php
$filename = './errors/test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

1 Answers

Adding length parameter in fwrite function worked for me.

replace write code with this. that might work.

// Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent,strlen($somecontent)) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }
Related