How to write data to a file
Short answer
file_put_contents() creates the file or replaces its content:
<?php
$file = sys_get_temp_dir() . '/recipe-write.txt';
file_put_contents($file, 'Hello');
echo file_get_contents($file);Output:
HelloAppending
The FILE_APPEND flag appends the data, and LOCK_EX guards against simultaneous writes:
<?php
$file = sys_get_temp_dir() . '/recipe-log.txt';
file_put_contents($file, "start\n");
file_put_contents($file, "finish\n", FILE_APPEND | LOCK_EX);
echo file_get_contents($file);Output:
start
finishThe folder does not exist yet
Create it before writing:
<?php
$dir = sys_get_temp_dir() . '/recipe-data/reports';
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($dir . '/today.txt', 'ok');
var_dump(file_exists($dir . '/today.txt'));Output:
bool(true)Functions used in this recipe
- file_put_contents — Writes data to a file.
- mkdir — Creates a folder.
- is_dir — Checks whether a path is a folder.