Handle Partial Writes and Zero Progress with PHP fwrite

Last updated: December 4, 2026.

Treat the result of fwrite() as a byte count. On a blocking writable stream, continue from the first unwritten byte after a short write. Stop when the call returns false or makes zero progress.

<?php

function writeAllBlocking($stream, string $data): void
{
    $length = strlen($data);
    $offset = 0;

    while ($offset < $length) {
        $chunk = substr($data, $offset, 8192);
        $written = fwrite($stream, $chunk);
        if ($written === false || $written === 0) {
            throw new RuntimeException("Write stopped at byte $offset");
        }

        $offset += $written;
    }
}

Advance by what the stream accepted

Open a writable stream in the caller, check that opening succeeded and pass the stream to the helper. Each iteration takes up to 8,192 bytes from the remaining input. If a call writes only 1,000 bytes, the next iteration starts 1,000 bytes later. Restarting from the beginning duplicates data already accepted by the stream.

When input is empty, the function returns without writing. Otherwise, a zero result indicates the call made no progress. Repeating that write indefinitely can spin even though no bytes are moving. Preserve PHP’s diagnostics and report the offset so the caller can distinguish an early failure from one that left partial output.

Keep ownership and failure handling at the call site

The caller owns the stream and closes it even if the helper throws. Check flush or close results if the destination buffers writes. A completed loop only establishes that the stream accepted the supplied bytes. It does not establish that another process received them or that the filesystem made them durable.

Use this helper for blocking streams. Nonblocking sockets need a different policy that waits for writability and enforces a deadline. For stored output that must appear complete, write to a separate file and promote it only after the write and close succeed.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov