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 ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.