×

php · level 2 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

file_put_contents saves text, file_get_contents reads it.

Variables vanish when your program ends. A stays on the disk afterwards, so a later run can read it. Every file has a : its full address, made of folders and then the file's name. In Gwecode, start each path with sys_get_temp_dir(), PHP's folder for scratch files.

file_put_contents($path, $text) writes text into a file, creating it if needed, and replaces whatever it held before. To instead, keeping the old text and adding to the end, pass FILE_APPEND as a third argument.

file_get_contents($path) reads the whole file back as one string.

<?php
$path = sys_get_temp_dir() . "/diary.txt";
file_put_contents($path, "Monday: sunny\n");
file_put_contents($path, "Tuesday: rain\n", FILE_APPEND);
echo file_get_contents($path);
file_put_contents($path, "Wednesday: snow\n");
echo "After replacing:\n" . file_get_contents($path);

Writing the first line without FILE_APPEND gives every run a fresh start, so old notes never pile up.