file_put_contents()

file_put_contents() — Write data to a file.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

Signature

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

Parameters

ParameterTypeWhat it takes
$filenamestringPath to the file where to write the data.
$datamixedThe data to write. Can be either a string, an array or a stream resource.
$flagsintThe value of flags can be any combination of the following flags, joined with the binary OR (|) operator.
$context?resourceA valid context resource created with stream_context_create().

Return value

This function returns the number of bytes that were written to the file, or false on failure. This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Example

A runnable snippet:

$file = 'people.txt'; // Open the file to get existing content $current = file_get_contents($file); // Append a new person to the file $current .= "John Smith\n"; // Write the contents back to the file file_put_contents($file, $current);

See also

fopen(), fwrite(), file_get_contents(), stream_context_create()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page file_put_contents() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.