Categories
PHP

Writing or Appending to Files

Writing to files is as easy as reading from them. In this tutorial, we’ll use the file_put_contents() and fwrite() functions to write and append to files. You’ll also learn how to lock files to avoid trouble when one process writes while the other one reads.

  1. file_put_contents()
  2. fwrite()
  3. flock() locking files

file_put_contents()

<?php
 $text = 'some text...';

 //Writing text to file
 $totalBytes = file_put_contents('file.txt', $text);

 //Appending text at the end of file
 $totalBytes = file_put_contents('file.txt', $text, FILE_APPEND); 

Writing to files is as easy as reading from them, the function file_put_contents() writes data directly to a file, and this is binary-safe. After calling the function, the file is closed. The code writes data into a file:

Example: Writing Data into a File

<?php
 $filename = 'file.txt';
 if ( ! is_writable($filename)) {
  die ("$filename is not writeable");
 }

 $lines = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec sollicitudin faucibus mollis.
Nullam ullamcorper eu sem a tristique.';

 $nbytes = file_put_contents($filename, $lines);

 if ($nbytes === false) {
  die ('Unable to write to file');
 }

 echo "Successfully written $nbytes bytes"; 

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

Example: Appending Data to a File:

The code appends data into a file:

<?php
 $lines = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec sollicitudin faucibus mollis.
Nullam ullamcorper eu sem a tristique.';

 $nbytes = file_put_contents('file.txt', $lines, FILE_APPEND);

 if ($nbytes === false) {
  die ('Unable to write to file');
 }

 echo "Successfully written $nbytes bytes"; 

Example: Prevent anyone else from writing to the file:

Use the LOCK_EX flag to prevent anyone from writing to the file at the same time:

<?php
 $lines = '....text....';

 //Writing while locking the file
 file_put_contents('file.txt', $lines, LOCK_EX);

 //Appending while locking the file
 file_put_contents('file.txt', $lines, FILE_APPEND | LOCK_EX);

fwrite()

See opening and closing files tutorial if you are not familiar with file flags and, fopen and fclose functions.

Example: Writing to file

<?php
 //Use "w" flag to write text to file
 $fp = fopen('file.txt', 'w');
 fwrite($fp, 'some text...');
 fclose($fp);

Example: Appending to file

<?php
 //Use "a" flag to write text to file
 $fp = fopen('file.txt', 'a');
 fwrite($fp, 'appending some text...');
 fclose($fp);

Writing to files with fwrite() function works similarly to reading from a file with fopen(), and fclose():

<?php
 $file = 'file.txt';
 $lines = "Line 1\nLine2";
 
 if ( ! is_writable($file)) {
  die ("$filename is not writeable");
 }

 //The "w" indicates open the file for writing
 $fp = fopen($file, 'w');
 if ($fp === false) {
  die ("Unable to open $file");
 }
 
 $totalBytes = fwrite($fp, $lines);
 
 if ($totalBytes === false) {
  die ("Unable to write to $file");
 }
 
 echo "Successfully written $totalBytes bytes";
 fclose($fp);

The fwrite() function writes (or appends) text to a file handle.

Locking Files

While reading and writing files, you have to take concurrency into mind. What if two processes try to access the file at the same time? To avoid trouble when one process writes while the other one reads, you have to lock the file. This is done using the PHP function flock().

<?php
 $fp = fopen('file.txt', 'w');
 if ( ! (flock ($fp, LOCK_EX) ) {
  exit ('Unable to lock the file');
 }

The first parameter is the file handle; the second one is the desired kind of locking to be used. The following options are available:

  • LOCK_EX Exclusive lock for writing
  • LOCK_NB Nonblocking lock
  • LOCK_SH Shared lock for reading
  • LOCK_UN Releasing a lock

Use the bitwise operator to apply two flags:

<?php
 $fp = fopen('file.txt', 'w');
 if ( ! flock($fp, LOCK_EX | LOCK_NB) ) {
  exit ('Lock failed');
 }

Example: Locking a file with flock function

<?php
 //Open file for writing
 $fp = fopen('file.txt', 'w');

 //Lock the file for writing
 flock($fp, LOCK_EX);

 //Write to file
 fwrite($fp, '..some text...');

 //Release the lock
 flock($fp, LOCK_UN);

 //Close the file
 fclose($fp);

Working with Files in PHP: