• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / PHP: Write and append to files with file_put_contents

PHP: Write and append to files with file_put_contents

The PHP file_put_contents() function is a useful shortcut for dumping a string into a file (compared with using fopen, fputs etc). By default it will create a new file if it does not exist, or overwrite the file if it does exist. Recently I re-read the documentation for this function and discovered it is also possible to append to a file with file_put_contents.

Writing to a new file / overwriting an existing file

Pass a filename and the string to write to the file (an array containing a stream can also be passed but that’s beyond the scope of this post) and either a new file will be created containing the contents of the string or an existing one will be overwritten with the contents of the string.

file_put_contents('/path/to/filename', $data);

Note that the directory you wish to write the file to must exist and be writable to as the user the script is running as. If overwriting an existing file then that file must be writable as the user the script is running as.

Appending to an existing file

As I discovered recently, it is also possible to append to an existing file using file_put_contents. The function can take a third parameter containing a list of flags joined with a binary OR operator.

To append to a file, pass the FILE_APPEND flag like so:

file_put_contents('/path/to/filename', $data, FILE_APPEND);

As with overwriting an existing file, the file must be writable as the user the script is running as.

Check Out These Related posts:

  1. Bash Check if File Exists
  2. Remove extension from a filename with PHP
  3. RFC 1321 – MD5 Message-Digest Algorithm
  4. Create a file in Linux

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap