[ Team LiB ] Previous Section Next Section

Writing Data to a File with file_put_contents()

The file_put_contents() function was introduced with PHP 5. It eliminates the need for opening and closing a file:

file_put_contents( "test2.txt", "Hello world\n" );

If you need to append to a file, you can pass a FILE_APPEND flag to the function, like so:

file_put_contents( "test2.txt", "And another thing\n", FILE_APPEND );

A second flag can be used with file_put_contents(). FILE_USE_INCLUDE_PATH creates the function to look in your include directories for the file to write to. This should be used with caution, if at all, because you could find yourself writing somewhere unexpected or undesirable if your include path is changed.

Locking Files with flock()

The techniques you have learned for reading and amending files will work fine if you are presenting your script to only a single user. In the real world, however, you would expect many users to access your projects more or less at the same time. Imagine what would happen if two users were to execute a script that writes to one file at the same moment. The file would quickly become corrupt.

PHP provides the flock() function to forestall this eventuality. flock() locks a file to warn other processes against writing to or reading from a file while the current process is working with it. flock() requires a valid file resource and an integer representing the type of lock you want to set. PHP provides predefined constants for each of the integers you are likely to need. Table 11.1 lists three kinds of locks you can apply to a file.

Table 11.1. Integer Arguments to the flock() Function



Lock Type





Allows other processes to read the file but prevents writing (used when reading a file)




Prevents other processes from either reading from or writing to a file (used when writing to a file)




Releases a shared or exclusive lock

You should call flock() directly after calling fopen() and then call it again to release the lock before closing the file:

$fp = fopen( "test.txt", "a" ) or die("couldn't open");
flock( $fp, LOCK_EX ); // exclusive lock
// write to the file
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );


Locking with flock() is advisory. Only other scripts that use flock() will respect a lock you set.

    [ Team LiB ] Previous Section Next Section