|[ Team LiB ]|
Writing Data to a File with file_put_contents()
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.
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 );
|[ Team LiB ]|