fputs

Writes a string to an open file stream; an alias of fwrite.

Signature
fputs(resource $stream, string $data, ?int $length = null): int|false
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$streamresourceAn open file pointer created by fopen(), fsockopen() or similar, not yet closed by fclose().
$datastringThe string to write.
$lengthoptional?int= nullIf given as an int, writing stops after this many bytes or at the end of data, whichever comes first.

Return value

int|falseReturns the number of bytes actually written, or false on failure.

Errors

Emits an E_WARNING on failure. It returns false, or a short byte count, rather than throwing.

Changelog

  • PHP 8.0.0length is nullable now.

fputs() is an alias of fwrite(). Same C function, same behaviour, same performance — the name exists for people coming from C's fputs(). New code should prefer fwrite(), which is the documented primary name, but there is nothing wrong with existing fputs() calls and no plan to remove it.

When to reach for it

  • Appending to a log or report line by line, where reopening the file per line with file_put_contents() would be wasteful.
  • Streaming a large payload out in chunks so it never has to sit in memory at once.
  • Writing to a socket or a pipe, where the whole point is incremental output.

What trips people up

The write is binary safe — no newline is added and no encoding conversion happens, so you must append "\n" yourself. Note fputs() and fputcsv() are unrelated despite the similar names.

The return value matters. On a non-blocking stream, a socket, or a nearly full disk, a short write is possible: the function returns fewer bytes than strlen($data) without returning false. Checking only if ($n === false) will silently drop data. For anything other than a plain local file, loop until everything is written.

Writes are buffered. Data is not on disk until fflush(), or fsync() if you need real durability.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Append request lines to an audit log opened once for the whole script run.
  • Stream a multi-gigabyte export to a file in chunks without loading it into memory.
  • Send a request line by line to a service over an already-open stream.

Frequently asked questions

What is the difference between fputs and fwrite?

There is none — fputs() is an alias of fwrite() and calls the identical implementation. fwrite() is the documented primary name and the better choice in new code.

Does fputs add a newline?

No. It writes exactly the bytes you pass, so you have to include "\n" yourself. It is also unrelated to fputcsv(), which formats and terminates a CSV row for you.

Why did fputs write fewer bytes than my string?

Short writes are normal on sockets, pipes and non-blocking streams, and can also happen when a disk fills up. Compare the return value with strlen($data) and write the remainder in a loop.

More examples

Handle a short write correctly

The loop trims off however many bytes were accepted and retries the rest, which is the only correct pattern once the stream is not a plain local file.

Example · php
<?php
function writeAll($fh, string $data): void {
    while ($data !== '') {
        $n = fputs($fh, $data);
        if ($n === false) {
            throw new RuntimeException('write failed');
        }
        $data = substr($data, $n);
    }
}

$fh = fopen('demo.txt', 'w');
writeAll($fh, str_repeat('payload ', 3));
fclose($fh);
echo file_get_contents('demo.txt'), "\n";
unlink('demo.txt');

Append log lines with one open handle

Opening once in append mode and writing repeatedly avoids the open/seek/close cycle that file_put_contents() with FILE_APPEND pays on every call.

Example · php
<?php
$log = fopen('app.log', 'a');
foreach (['boot', 'connect', 'ready'] as $event) {
    fputs($log, gmdate('H:i:s', 0) . " $event\n");
}
fclose($log);

echo file_get_contents('app.log');
unlink('app.log');

fputs and fwrite are the same function

Both calls return 3 and both advance the same pointer, producing "abcdef". There is no behavioural difference to choose between them.

Example · php
<?php
$fh = fopen('demo.txt', 'w+');
var_dump(fputs($fh, 'abc'));
var_dump(fwrite($fh, 'def'));

rewind($fh);
echo fread($fh, 16), "\n";
fclose($fh);
unlink('demo.txt');

Discussion

  • Be the first to comment on this lesson.