Challenge - File and session
Build a simple notebook app with file read/write and sessions.
Challenge - File and session
In this challenge you'll build a simple notebook app. The saveNote(string $note): void function writes a note to a file; readNotes(): string returns the file's full contents. The logged-in user's name lives in the $_SESSION superglobal.
You write with file_put_contents and read with file_get_contents. The FILE_APPEND flag appends each new note; without it every write overwrites the file. session_start must run before any output.
file_put_contents and file_get_contents
file_put_contents takes three arguments: the file path, the text to write, and an optional flag. With FILE_APPEND it appends; without the flag it resets the file. End each note with a newline to keep them apart.
file_get_contents returns the whole file as one string. If the file is missing it returns false; using ?: "" gives a safe empty-string default. The session_start call belongs at the top of the page.
Exercise Write saveNote and readNotes functions
First call session_start(). Define saveNote(string $note): void that writes the note with file_put_contents("notes.txt", $note . "\n"). Define readNotes(): string that reads the file with file_get_contents("notes.txt") ?: "". Then assign $_SESSION["user"] = "Alex", call saveNote("Meeting note"), and run echo $_SESSION["user"] . ": " . readNotes().
Show example solution
Call session_start() first; define both functions; set $_SESSION["user"] and echo it.
Example solution:
<?php
// Write saveNote and readNotes functions
session_start();
function saveNote(string $note): void {
file_put_contents("notes.txt", $note . "\n");
}
function readNotes(): string {
return file_get_contents("notes.txt") ?: "";
}
$_SESSION["user"] = "Alex";
saveNote("Meeting note");
echo $_SESSION["user"] . ": " . readNotes();
Test yourself
-
When should session_start() be called?
- Before any output
- At the very end of the page
- After every echo
- Only on errors
Show answer
Before any output — Correct. session_start() runs before any output; the session cookie is sent as an HTTP header.
-
Add the FILE_APPEND flag
file_put_contents("notes.txt", $note . "\n", ____);Show answer
file_put_contents("notes.txt", $note . "\n", FILE_APPEND); -
Match each function to its job
- file_put_contents
- writes to file
- file_get_contents
- reads from file
- session_start
- starts session
- $_SESSION
- holds session data