int file_put_contents ( string filename, string data [, int flags [, resource context]])

This function writes to a file with the equivalent of fopen(), fwrite() (the opposite of fread() ), and fclose() - all in one function, just like file_get_contents. It takes two parameters, the filename to write to and the content to write respectively, with a third optional parameter specifying extra flags which we will get to in a moment. If file_put_contents() is successful it returns the number of bytes written to the file, otherwise it will return false.

Using the file_put_contents() function is easy - here's an example:

    $myarray[] = "This is line one";
    $myarray[] = "This is line two";
    $myarray[] = "This is line three";
    $mystring = implode("\n", $myarray);
    $numbytes = file_put_contents($filename, $mystring);
    print "$numbytes bytes written\n";

Remember you will need to set $filename first - other than that the script is straightforward, and should output "52 bytes written", which is the sum total of the three lines of text plus the two new line characters used to implode() the array. Remember that the new line character is in fact just one character inside files, whereas PHP represents it using two, \ and n.

You can pass in a third parameter to file_put_contents(), which, if set to FILE_APPEND, will act to append the text in your second parameter to the existing text in the file. If you do not use FILE_APPEND the existing text will be wiped and replaced, which is not always the desired behaviour.


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: fwrite() >>

Previous chapter: Creating and changing files

Jump to:


Home: Table of Contents

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