Write to file in PHP

Dani 0 Tallied Votes 2K Views Share

There are two ways to write to a file in PHP. You can either open a stream, and write to it in parts, or you can use file_put_contents() which is much more convenient, with the trade off being that it takes up much more memory, and is not ideal if you want to send a lot of data upstream.

<?php

// Method 1

$contents = "Foo bar";
$more_contents = "Baz bat";
$filename = "example.txt";

// We use 'w' to open for writing, placing the pointer at the beginning of a blank file
// We use 'a' to open for writing, placing the pointer at the end of the file for appending
$handler = fopen($filename, "w");

fwrite($handler, $contents);
fwrite($handler, $more_contents);
fclose($handler);

// Method 2

// To write contents to a file
file_put_contents($filename, $contents . ' ' . $more_contents);

// To append contents to an existing file
file_put_contents($filename, $contents . ' ' . $more_contents, FILE_APPEND);