php · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three writes, one file. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$path = sys_get_temp_dir() . "/scores.txt";
file_put_contents($path, "10\n");
file_put_contents($path, "20\n");
file_put_contents($path, "30\n", FILE_APPEND);
echo file_get_contents($path);
your turn
Your turn. Keep a to-do list.
Type two more jobs for the list, one in each blank. Run it and read the file back.
fix it
Three guests signed in, but only Cleo is left. Fix it.
- Every write on lines 4 and 5 replaces what the file held. What would keep the old names?
- Pass
FILE_APPENDas a third argument so new names go on the end. - Add
, FILE_APPENDinside the brackets on lines 4 and 5, then press run.
nailed it
your program can keep notes now. :D
file_put_contentswrites text and replaces the old.FILE_APPENDadds to the end instead.file_get_contentsreads the whole file back.
new words in your collection
- file
- path
- append
This lesson isn’t saved. A free account remembers every lesson you finish.