Chapter 11

Files, JSON, and Sessions

Data that outlives one run has to be written somewhere. Learn files, JSON and sessions, and learn where each of them stops being the right answer.

Chapter 11, Files, JSON, and Sessions

What you will learn

  • Read and write files safely for small practice applications.
  • Encode and decode JSON with explicit error handling.
  • Start and use a PHP session before output.
  • Choose between file persistence and session state based on purpose.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

11.1 Reading and Writing Files

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$text = "First note" . PHP_EOL;

file_put_contents("notes.txt", $text);
file_put_contents("notes.txt", "Second note" . PHP_EOL, FILE_APPEND);

echo file_get_contents("notes.txt");

11.2 JSON as a Data Boundary

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$task = ["title" => "Practice PHP", "done" => false];

$json = json_encode($task, JSON_THROW_ON_ERROR);
echo $json . PHP_EOL;

$back = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
var_dump($back["done"]);

11.3 Sessions

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

session_start();

$_SESSION["cart"] ??= [];
$_SESSION["cart"][] = "notebook";

echo "Items in cart: " . count($_SESSION["cart"]) . "";

TPRM Lab 11.1: Save and Restore JSON

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$tasks = [
    ["title" => "Practice PHP", "done" => false],
    ["title" => "Test JSON", "done" => true]
];

$json = json_encode($tasks, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
file_put_contents("tasks.json", $json);

$loadedText = file_get_contents("tasks.json");
$loaded = json_decode($loadedText, true, 512, JSON_THROW_ON_ERROR);

echo count($loaded) . PHP_EOL;
echo $loaded[0]["title"] . PHP_EOL;

TPRM Lab 11.2: A Session Counter

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

session_start();

$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;

echo "Visits this session: " . $_SESSION["visits"];

Back to PHP the TPRM Way