file_put_contents
Writes data to a file.
Syntax
file_put_contents(string $filename, mixed $data, int $flags = 0): int|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $filename | string | The path to the file. |
| $data | mixed | A string or an array of strings. |
| $flags | int | Optional. `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
HelloAppending 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
secondNotes
If several visitors may change the file at once, add LOCK_EX, or the writes get mixed up.
See also
- file_get_contents — Reads a whole file into a string.
- mkdir — Creates a folder.
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.