fwrite()
The fwrite() function is a built-in PHP function that writes data to a file. This function is used to write data to a file at the current position of the file
What Is the fwrite() Function?
fwrite() is a built-in PHP function that writes a string to an open file. It writes starting at the current position of the file pointer and advances that pointer by the number of bytes written, so consecutive calls append to one another rather than overwriting. It is the standard low-level way to write to files in PHP and is also commonly aliased as fputs() (the two are identical).
This page covers the syntax, the optional length argument, the file modes that control where and how data is written, return values, error handling, and the everyday tasks you'll reach for fwrite() to do.
Syntax
fwrite(resource $stream, string $data, ?int $length = null): int|false| Parameter | Required | Description |
|---|---|---|
$stream | Yes | A file pointer (resource) returned by fopen(). |
$data | Yes | The string to write. |
$length | No | If given, writing stops after $length bytes — whichever comes first, the end of $data or this limit. |
Return value: the number of bytes actually written, or false on failure. Because a short write (fewer bytes than strlen($data)) is possible on some streams, robust code checks the return value rather than assuming success.
You almost never need the
lengthargument.fwrite($file, $data)already writes the whole string. Pass a length only when you deliberately want to truncate the output to the first N bytes.
A Basic Example
<?php
$filename = 'myfile.txt';
$file = fopen($filename, 'w'); // open for writing (truncates the file)
if ($file === false) {
exit("Could not open $filename for writing");
}
$bytes = fwrite($file, "Hello, world!");
fclose($file);
echo "Wrote $bytes bytes."; // Wrote 13 bytes.Three steps are always involved:
- Open the file with
fopen()in a mode that permits writing. - Call
fwrite()one or more times to push data into the stream. - Close the file with
fclose()to flush the buffer and release the handle.
"Hello, world!" is 13 characters, so fwrite() returns 13.
File Modes: Where the Bytes Go
The behaviour of fwrite() is decided almost entirely by the mode you passed to fopen(). This is the most common source of confusion, so it's worth memorizing:
| Mode | Meaning | Existing content |
|---|---|---|
'w' | Write only | Truncated to empty, then written from the start |
'w+' | Read + write | Truncated, then written |
'a' | Append only | Preserved; every write goes to the end |
'a+' | Read + append | Preserved; writes go to the end |
'x' | Exclusive write | Fails if the file already exists (prevents overwrites) |
'r+' | Read + write | Preserved; writes start at the beginning, overwriting byte-by-byte |
If your file keeps coming out empty or losing yesterday's data, you almost certainly opened it with 'w' when you meant 'a'.
Appending Instead of Overwriting
<?php
$log = fopen('app.log', 'a'); // 'a' keeps existing lines
fwrite($log, "User logged in\n"); // \n adds a newline
fwrite($log, "Order placed\n");
fclose($log);Each run of this script adds two more lines to app.log instead of wiping it.
Writing Multiple Lines
fwrite() writes exactly the bytes you give it — it does not add line breaks. Include \n yourself (inside double quotes, so the escape is interpreted):
<?php
$file = fopen('names.txt', 'w');
$names = ['Alice', 'Bob', 'Carol'];
foreach ($names as $name) {
fwrite($file, $name . PHP_EOL); // PHP_EOL = OS-correct line ending
}
fclose($file);PHP_EOL resolves to \n on Unix/macOS and \r\n on Windows, which keeps text files portable.
Always Check the Return Value
Disk-full conditions, permission problems, and broken pipes all cause writes to fail or fall short. Treat the return value as the source of truth:
<?php
$file = fopen('report.txt', 'w');
if ($file === false) {
throw new RuntimeException('Unable to open report.txt');
}
$data = str_repeat('x', 1000);
$written = fwrite($file, $data);
if ($written === false || $written < strlen($data)) {
fclose($file);
throw new RuntimeException('Write failed or incomplete');
}
fclose($file);
echo "OK: $written bytes written";fwrite() vs file_put_contents()
For a single, one-shot write, file_put_contents() is shorter — it opens, writes, and closes in one call:
<?php
// Equivalent of the basic example above, in one line:
file_put_contents('myfile.txt', 'Hello, world!');Prefer fwrite() when you need to keep the file open across many writes (loops, streaming, logging), pass options like locking, or write incrementally without rebuilding the whole string in memory.
Common Gotchas
'w'truncates immediately — the momentfopen($f, 'w')succeeds, the old contents are gone, even if you never callfwrite().- No automatic newlines — you must add
\n/PHP_EOLyourself. - Forgetting
fclose()— data may sit in a buffer and never reach disk until the handle is closed (or the script ends). - Single quotes don't expand escapes —
'Line\n'writes a literal backslash-n. Use"Line\n"for a real newline. - The
lengthcap is in bytes — with multi-byte UTF-8 text, a byte limit can cut a character in half.
Conclusion
fwrite() is PHP's core function for writing strings to an open file. Master the three-step open–write–close cycle, pick the right fopen() mode ('w' to replace, 'a' to append), add your own newlines, and check the return value, and you can write everything from quick text files to durable application logs.
Related Functions
fopen()— open the file before writingfclose()— flush and close the handle afterwardfread()andfgets()— read the data backfile_put_contents()— write a whole file in one callfeof()— detect the end of a file while reading