OSPHP.009: PHP File Handling and JSON — Reading, Writing and Validating Persistent Data

Conceptual programming workstation and persistent storage drive illustrating PHP JSON file handling.

Open-Source PHP Programming • Intermediate • Estimated study time: 40 minutes.

File persistence preserves data beyond the lifetime of a PHP process. Unlike a variable that disappears when a script terminates, a file can retain bytes for a subsequent process. JSON (JavaScript Object Notation) provides a language-independent text representation of structured information. The previous sessions and cookies lesson introduced request-to-request state; file handling extends the course to application-owned storage.

Prerequisites and learning objectives

Install PHP 8.4 or a compatible supported PHP 8 release and review CLI execution, associative arrays and exception handling. By completion, learners should be able to encode and decode JSON, detect file operation failures, validate decoded records, handle malformed data without confusing it with legitimate zero values, and explain file locking and its limitations. Run the laboratory locally using synthetic measurements, not production files, customer data or secrets.

Serialization and deserialization

Serialization transforms an in-memory value into bytes suitable for transmission or storage. The PHP manual documents json_encode for serialization and json_decode for deserialization. With the second decode argument set to true, JSON objects become associative arrays. JSON_THROW_ON_ERROR converts encoding or decoding failures into JsonException rather than relying on a separate error-status check. A valid JSON document can still contain an invalid application record; checking syntax alone cannot establish correctness.

Traversy Media demonstrates reading and interpreting JSON data with PHP. The older introductory video illustrates the basic conversion; the laboratory uses modern exception-based error handling. Watch at source.

Reading, writing and detecting errors

The file_put_contents reference describes a whole-file write and its returned byte count. The file_get_contents reference describes reading a file into a string. Both operations may fail and emit warnings. Test the returned result with strict comparison against false. An empty string or zero-byte write is not necessarily a failed operation. Use a trusted local pathname rather than concatenating arbitrary request parameters into a path.

Program With Gio explains PHP filesystem operations, including reading files and writing content with file_put_contents. Watch at source.

Laboratory: a synthetic rack-temperature record

A record contains a rack identifier and an integer temperature in degrees Celsius. The program creates a disposable temporary file, encodes and writes a record, reads it back, checks the decoded fields, then exercises malformed input and an incorrect field type. The program removes its temporary file in a finally block. Save the following complete program as rack_lab.php:

<?php
declare(strict_types=1);
 
function saveReading(string $path, array $record): void {
    $json = json_encode($record, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
    $bytes = file_put_contents($path, $json, LOCK_EX);
    if ($bytes === false || $bytes !== strlen($json)) {
        throw new RuntimeException('Incomplete write');
    }
}
 
function loadReading(string $path): array {
    $json = file_get_contents($path);
    if ($json === false) {
        throw new RuntimeException('Read failed');
    }
    $record = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    if (!is_array($record) || !isset($record['rack'], $record['temp_c']) ||
        !is_string($record['rack']) || !is_int($record['temp_c'])) {
        throw new UnexpectedValueException('Invalid record');
    }
    return $record;
}
 
$path = tempnam(sys_get_temp_dir(), 'rack-');
if ($path === false) {
    throw new RuntimeException('Cannot create lab file');
}
try {
    saveReading($path, ['rack' => 'A', 'temp_c' => 24]);
    $record = loadReading($path);
    echo $record['rack'], ': ', $record['temp_c'], " C\n";
    if ($record !== ['rack' => 'A', 'temp_c' => 24]) {
        throw new RuntimeException('Round trip failed');
    }
    echo "PASS round trip\n";
    saveReading($path, ['rack' => 'A', 'temp_c' => 0]);
    if (loadReading($path)['temp_c'] !== 0) {
        throw new RuntimeException('Zero lost');
    }
    echo "PASS zero preserved\n";
    file_put_contents($path, '{bad');
    try {
        loadReading($path);
        throw new RuntimeException('Malformed JSON accepted');
    } catch (JsonException $e) {
        echo "PASS malformed JSON rejected\n";
    }
    file_put_contents($path, '{"rack":"A","temp_c":"24"}');
    try {
        loadReading($path);
        throw new RuntimeException('Wrong type accepted');
    } catch (UnexpectedValueException $e) {
        echo "PASS wrong type rejected\n";
    }
} finally {
    unlink($path);
}

Open a terminal in the directory containing rack_lab.php and run the following commands:

php -l rack_lab.php
php rack_lab.php

The laboratory was syntax-checked and executed using PHP 8.4.24. The following output was observed:

A: 24 C
PASS round trip
PASS zero preserved
PASS malformed JSON rejected
PASS wrong type rejected

Understanding each verification

The first test checks whether the decoded record is identical to the original associative array. The second preserves an integer zero; using a truthiness check would confuse zero with missing data. The third intentionally writes invalid JSON and verifies that parsing raises JsonException. The fourth supplies syntactically valid JSON with a string instead of an integer and verifies rejection by the record-validation function. The laboratory demonstrates both syntactic and semantic validation. A valid measurement of zero is not evidence that a sensor has failed.

Locking, concurrency and durability

LOCK_EX requests an exclusive lock during the file write. It does not guarantee that an unrelated reader acquires a shared lock, nor does it make an entire read-modify-write sequence atomic. An interrupted write can leave partial content. Cooperating processes need a consistent locking protocol; production systems may use a carefully designed temporary-file replacement strategy or a transactional database. Whole-file reads also consume memory proportional to file size. Large datasets may require streaming, record-oriented storage or a database. Store sensitive data outside public document roots and apply least-privilege filesystem permissions. The laboratory uses a trusted temporary file and a single process, not a multi-user database.

Exercises and answer key

Exercise 1: Replace the saved temperature with -5 and predict the decoded type. Exercise 2: Explain why an empty file should not be mistaken for false. Exercise 3: Replace the JSON input with a record missing temp_c and predict the exception. Exercise 4: Explain why LOCK_EX during a write cannot protect an earlier read. Exercise 5: Describe why a JSON string containing digits should not automatically become an integer measurement.

Answers: 1. The value remains an integer and satisfies the current schema. 2. A successful read can return an empty string, whereas false denotes failure; empty text still fails JSON decoding. 3. UnexpectedValueException because the required field is absent. 4. Another process may change the file between reading and acquiring the write lock. 5. Automatic conversion can hide input-schema errors; type conversion should be an explicit policy.

Conclusion

PHP file operations and JSON serialization offer a useful foundation for configuration files, small local datasets and data exchange. Check filesystem failures, validate the application schema independently of JSON syntax, preserve legitimate zero values and choose storage mechanisms appropriate to concurrency and durability requirements.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply