fwrite()
fwrite() — Binary-safe file write.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
fwrite() writes the contents of data to the file stream pointed to by stream.
Signature
fwrite(resource $stream, string $data, ?int $length = null): int|false
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $stream | resource | A file system pointer resource that is typically created using fopen(). |
| $data | string | The string that is to be written. |
| $length | ?int | If length is an int, writing will stop after length bytes have been written or the end of data is reached, whichever comes first. |
Return value
fwrite() returns the number of bytes written, or false on failure.
Example
A runnable snippet:
$filename = 'test.txt'; $somecontent = "Add this to the file\n"; // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$fp = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($fp, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename)"; fclose($fp); } else { echo "The file $filename is not writable"; }
Changelog
| Version | Change |
|---|---|
| 8.0.0 | length is nullable now. |
See also
fread(), fopen(), fsockopen(), popen(), file_get_contents(), pack()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page fwrite() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.