Prepending to a File

Problem

You want to write content to the beginning of a file.

Solution

Use the File::prepend() method.

$bytesWritten = File::prepend($filename, $content);
if ($bytesWritten === false)
{
    die("Couldn't write to the file.");
}

This will add the content to the beginning of existing files. If the file doesn't exist then the entire contents will be $content.

Discussion

Watch the return value.

If there's a problem writing to the file false is returned.

comments powered by Disqus