← All writing

Check how many bytes file_put_contents actually wrote

PHP 8.3+Sources checked 2026-09-13

A small export file is empty by design, but a loose check reports that writing it failed. file_put_contents returns the number of bytes written or false on failure. Writing an empty string can successfully return zero.

Compare the result strictly

<?php
$path = tempnam(sys_get_temp_dir(), 'writing-');
if ($path === false) throw new RuntimeException('Cannot create temporary file');
try {
    $written = file_put_contents($path, '');
    assert($written === 0);
    assert($written !== false);
} finally {
    unlink($path);
}

For nonempty content, compare the returned count to the expected byte length when complete output matters. A success label should reflect the finished write, not merely the fact that the function was called.

Publishing a file has a visibility boundary

A reader may observe an incomplete file if you overwrite a public artifact directly. For an appropriate local filesystem, write a temporary file in the destination directory, verify it, and rename it into place. Confirm the rename semantics of the actual filesystem and avoid assuming a cross-filesystem move is atomic.

Set permissions suitable for the intended audience. A public image copied from a desktop may retain owner-only permissions and return 403 even when its path is correct. Conversely, a private backup should not be made world-readable to solve a public asset issue.

Test an empty export, a normal export, an unwritable destination, and replacement while readers are active. Avoid using @ to hide filesystem warnings without also reporting a meaningful application failure. Silent failure is particularly damaging in scheduled exports where no user is watching the request.

Reference

Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.