W3docs

file_put_contents()

The file_put_contents() function is a built-in PHP function that writes data to a file. This function creates the file if it does not exist and overwrites the

The file_put_contents() function writes a string to a file in a single call. It is the modern, one-line replacement for the classic fopen()fwrite()fclose() sequence: PHP opens the file, writes the data, and closes the handle for you. This page covers its syntax, parameters, return value, flags for appending and locking, and the mistakes that most often trip people up.

Syntax

file_put_contents(string $filename, mixed $data, int $flags = 0, ?resource $context = null): int|false

Parameters

ParameterRequiredDescription
$filenameYesPath of the file to write. If it does not exist, PHP creates it.
$dataYesThe data to write — a string, an array of strings (joined with no separator, like implode('', $array)), or a stream resource whose remaining contents are copied.
$flagsNoA bitmask: FILE_APPEND, LOCK_EX, and/or FILE_USE_INCLUDE_PATH. Defaults to 0 (overwrite).
$contextNoA stream context resource created with stream_context_create(), for example to set HTTP headers when writing to a remote stream.

Return value

file_put_contents() returns the number of bytes written, or false on failure. Because 0 is a valid (falsy) result when you write an empty string, always check failure with the strict === false comparison rather than a loose truthiness test.

Writing a file

By default the function overwrites the file's existing contents (or creates the file if it is missing):

<?php

$filename = 'myfile.txt';
$data     = 'This is some data to be written to the file.';

$bytes = file_put_contents($filename, $data);

if ($bytes === false) {
    echo "Failed to write to $filename";
} else {
    echo "Wrote $bytes bytes to $filename";
}

Output:

Wrote 44 bytes to myfile.txt

The returned count, 44, is the length of the string in bytes.

Appending instead of overwriting

Pass the FILE_APPEND flag to add to the end of the file rather than replacing its contents — handy for log files:

<?php

$log = 'app.log';

file_put_contents($log, "First line\n", FILE_APPEND);
file_put_contents($log, "Second line\n", FILE_APPEND);

echo file_get_contents($log);

Output:

First line
Second line

Without FILE_APPEND, the second call would erase the first line.

Locking the file while writing

If several processes might write to the same file at once, add LOCK_EX to acquire an exclusive lock for the duration of the write. Combine flags with the bitwise OR operator (|):

<?php

file_put_contents('counter.txt', "ping\n", FILE_APPEND | LOCK_EX);

This prevents two writers from interleaving their output and corrupting the file.

Writing an array

When $data is an array, its string elements are concatenated with no separator. Glue them yourself if you need delimiters:

<?php

$lines = ['apple', 'banana', 'cherry'];

file_put_contents('fruits.txt', implode("\n", $lines));

echo file_get_contents('fruits.txt');

Output:

apple
banana
cherry

Common gotchas

  • Silent failure on permissions. If the directory is not writable, the call returns false and emits a warning — it does not throw. Check the return value (=== false) or wrap the call and inspect error_get_last().
  • The parent directory must exist. file_put_contents() creates the file but not missing directories. Call mkdir($dir, 0777, true) first if needed.
  • FILE_APPEND is not the same as overwrite. Forgetting the flag is the most common cause of "my log keeps getting wiped."
  • Empty data is valid. Writing '' returns 0, which is falsy — use === false so you don't mistake a successful empty write for an error.
  • file_get_contents() — the read counterpart that slurps a whole file into a string.
  • fwrite() — lower-level writing when you need an open handle (e.g. many small writes in a loop).
  • fopen() — open a file handle for streamed reading or writing.
  • file_exists() — check whether a file is present before writing.

Conclusion

file_put_contents() is the simplest way to write a string to a file in PHP: one call opens, writes, and closes the file. Reach for FILE_APPEND to add to a file, LOCK_EX for concurrent writers, and always verify success with a strict === false check.

Practice

Practice
What does the PHP file_put_contents() function do?
What does the PHP file_put_contents() function do?
Was this page helpful?