int fwrite ( resource handle, string string [, int length])

The opposite to fread() is fwrite() and also works with the file handle returned by fopen(). Fwrite() takes a string to write as a second parameter, and an optional third parameter where you can specify how many bytes to write. If you do not specify the third parameter, all of the second parameter is written out to the file, which is often what you want.

Author's Note: as with fread(), PHP will stop writing when it reaches the end of the string or when it has reached the number of bytes specified in this length parameter, whichever comes first - you don't need to worry about specifying more bytes than you have in the string.

Here is an example using the variable $mystring from the previous example to save space:

    $handle = fopen($filename, "wb");
    $numbytes = fwrite($handle, $mystring);
    print "$numbytes bytes written\n";

If I had added 10 as the third parameter to the fwrite() call, only the first ten bytes of $mystring would have been written out. Note again that fclose() is called immediately after it was finished with, which is always best practice.

Fwrite() uses a file pointer in the same way as fread() - as you write bytes out, PHP advances the file pointer appropriately, meaning that, unless you specifically move the file pointer yourself, you always write to the end of a file.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Moving, copying, and deleting files >>

Previous chapter: file_put_contents()

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.