Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

Hello

Appending

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
finish

The 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

Thanks for reading!

Donate to the site — we work hard for you.