PHP fwrite() Function
Quick summary: The PHP fwrite() function writes data to an open file pointer.
PHP fwrite() Syntax
fwrite(resource $stream, string $data, ?int $length = null): int|false
PHP
PHP fwrite() Basic examples
$h = fopen('test.txt', 'w');
var_dump(fwrite($h, 'Hello'));
fclose($h);
PHP
Output:
int(5)
Writes data and returns the number of bytes written.
PHP fwrite() Real-world usage
$h = fopen('app.log', 'a');
fwrite($h, "Log entry\n");
fclose($h);
PHP
Output:
int(...)
Appends log entries to a file.
PHP fwrite() Edge cases
var_dump(fwrite(null, 'x'));
PHP
Output:
Warning: fwrite(): supplied resource is not a valid stream resource
fwrite requires a valid file handle.
PHP fwrite() Common mistakes
Ignoring partial writes
fwrite may write fewer bytes than expected.
Incorrect
fwrite($h, $data);
Correct
while ($written < strlen($data)) { $written += fwrite($h, substr($data, $written)); }
Ensure all data is written.
PHP fwrite() Frequently Asked Questions
What does fwrite() do?
Writes data to an open file pointer.
Requires fopen()?
Yes.
Return value?
Number of bytes written.
Use case?
Writing data to files.
Handles binary?
Yes.
Performance?
Efficient.
Common mistake?
Ignoring partial writes.
Can append?
Yes with correct mode.
Error handling?
Check return value.
Alternative?
file_put_contents().
Safe?
Yes.
Flush needed?
Sometimes.