Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP file_put_contents() function

Reference for PHP file_put_contents(): write a string or array to a file in one call, FILE_APPEND, LOCK_EX, the bytes-written return value and failure handling.

file_put_contents() writes data to a file in a single call. It opens the file, writes, and closes it, replacing the existing contents unless you pass the FILE_APPEND flag. It is the counterpart of file_get_contents() and the quickest way to save a string.

It returns the number of bytes written, or false on failure. Combine FILE_APPEND with LOCK_EX to append to a shared log without two requests mixing their lines.

PHP
file_put_contents("greeting.txt", "Hello\n");
file_put_contents("greeting.txt", "More\n", FILE_APPEND | LOCK_EX);

Try it

PHP Overwrite and append

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Arrays, numbers and failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
file_put_contents(
    string $filename,
    mixed $data,
    int $flags = 0,
    ?resource $context = null
): int|false
Name Description
$filename The file to write. It is created if it does not exist (the directory must exist).
$data A string, an array (items are concatenated, no separators), or a stream resource. Other scalars are converted to strings.
$flags Combination of FILE_APPEND, LOCK_EX and FILE_USE_INCLUDE_PATH.
$context Optional stream context.

Return value: the number of bytes written, or false on failure.

Errors: a warning is raised when the file cannot be opened or written.

Usage notes

  • It overwrites by default. Without FILE_APPEND, existing content is lost, even if writing fails halfway.
  • Check === false. Writing an empty string returns 0, which is a success.
  • Arrays are joined without separators. Add "\n" yourself or use implode("\n", $lines).
  • Use LOCK_EX when several processes may write at once. It takes an exclusive lock for the duration of the write.
  • Missing directories are not created. Call mkdir($dir, 0777, true) first.
  • Atomic replacement: write to a temporary file in the same directory, then rename() it over the target, so readers never see a half-written file.
  • Permissions of a new file follow the process umask; set them with chmod() if needed.
  • Large data: for very large output, use a handle with fwrite() to avoid building one huge string.