fwrite

PHP 4, PHP 5, PHP 7, PHP 8
fwrite - Binary-safe file write
Manual
Code Examples

fwrite( resource$stream, string$data, [int|null$length = null] ): int|false

fwrite writes the contents of data to the file stream pointed to by stream.

Parameters

stream

A file system pointer resource that is typically created using fopen.

data

The string that is to be written.

length

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 Values

fwrite returns the number of bytes written, or false on error.

Notes

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite may be checked:

<?php
function fwrite_stream($fp$string) {
    for (
$written 0$written strlen($string); $written += $fwrite) {
        
$fwrite fwrite($fpsubstr($string$written));
        if (
$fwrite === false) {
            return 
$written;
        }
    }
    return 
$written;
}
?>

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen mode parameter.

Note:

If stream was fopened in append mode, fwrites are atomic (unless the size of data exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock a resource before calling fwrite; all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp 
fopen('data.txt''w');
fwrite($fp'1');
fwrite($fp'23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

Changelog

Version Description
8.0.0 length is nullable now.

Related Functions

Example of fwrite

Show all examples for fwrite

PHP Version: