Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

file_put_contents

Writes data to a file.

Syntax

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

Parameters

ParameterTypeDescription
$filenamestringThe path to the file.
$datamixedA string or an array of strings.
$flagsintOptional. `FILE_APPEND` appends to the end, `LOCK_EX` locks the file while writing.

Return value

int|falseThe number of bytes written, or `false` on failure.

Examples

Writing replaces the content of the file:

<?php
 
$file = sys_get_temp_dir() . '/ref-write.txt';
 
echo file_put_contents($file, 'Hello'), "\n";
echo file_get_contents($file);

Output:

5
Hello

Appending to the end:

<?php
 
$file = sys_get_temp_dir() . '/ref-log.txt';
file_put_contents($file, "first\n");
file_put_contents($file, "second\n", FILE_APPEND);
 
echo file_get_contents($file);

Output:

first
second

Notes

If several visitors may change the file at once, add LOCK_EX, or the writes get mixed up.

See also

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.