Reading and writing files
Variables live only while the program runs. To keep data between runs, you write it to a file or a database. Files are easy in PHP: one function is enough for each basic action.
Writing to a file
file_put_contents() takes a file path and some text. If the file does not exist it is created; if it does, it is replaced:
<?php
$file = sys_get_temp_dir() . '/notes.txt';
file_put_contents($file, 'Buy milk');The program prints nothing — it only creates the file. sys_get_temp_dir() returns the folder for temporary files; a real project would use the path to its data folder here.
Reading a file
file_get_contents() returns the whole content of a file as one string:
<?php
$file = sys_get_temp_dir() . '/notes.txt';
file_put_contents($file, 'Buy milk');
echo file_get_contents($file);Appending
To add text to the end instead of replacing the file, pass the FILE_APPEND flag. The PHP_EOL constant is a line break:
<?php
$file = sys_get_temp_dir() . '/notes.txt';
file_put_contents($file, 'Buy milk' . PHP_EOL);
file_put_contents($file, 'Call mum' . PHP_EOL, FILE_APPEND);
echo file_get_contents($file);Reading line by line
file() returns an array of the file's lines. The FILE_IGNORE_NEW_LINES flag strips the line break at the end of each:
<?php
$file = sys_get_temp_dir() . '/notes.txt';
file_put_contents($file, "Milk\nBread\nCheese");
$lines = file($file, FILE_IGNORE_NEW_LINES);
foreach ($lines as $number => $line) {
echo $number + 1, '. ', $line, "\n";
}Checking and deleting
file_exists() tells you whether a file exists, and unlink() deletes it:
<?php
$file = sys_get_temp_dir() . '/notes.txt';
file_put_contents($file, 'Temporary data');
var_dump(file_exists($file)); // bool(true)
unlink($file);
var_dump(file_exists($file)); // bool(false)A common mistake
If the file is missing, file_get_contents() raises a warning and returns false. Check the file with file_exists() before reading.
The second trap is relative paths: they are resolved from the folder the script was started in, which varies. It is safer to build the path from the __DIR__ constant — the folder of the current file: __DIR__ . '/data/notes.txt'.