Skip to main content

Lesson 6 of 6

Mini Project: Blog System - Part 8 (JSON Config, CSV Export & Media Upload)

Extend the Blog System with: JSON-based application configuration with environment override, CSV export of published posts for SEO/analytics tools, and an image media library that organises uploads by date, generates thumbnails, and serves files via a secure media controller.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Blog Part 8 - File Handling Features

Blog Part 8 - File Handling Features
<?php
declare(strict_types=1);

// ── JSON Config with env overrides ────────────────────────────
class Config {
    private array $config;

    public function __construct(string $configPath) {
        $base         = json_decode(file_get_contents($configPath), true, flags: JSON_THROW_ON_ERROR);
        $envOverrides = json_decode(file_get_contents(
            str_replace(".json", ".{$_ENV['APP_ENV']}.json", $configPath)
        ) ?: "{}", true, flags: JSON_THROW_ON_ERROR);

        $this->config = array_replace_recursive($base, $envOverrides);
    }

    public function get(string $key, mixed $default = null): mixed {
        $keys  = explode(".", $key);
        $value = $this->config;
        foreach ($keys as $k) {
            $value = $value[$k] ?? null;
            if ($value === null) return $default;
        }
        return $value;
    }
}

$config = new Config(__DIR__ . "/../config/app.json");
$perPage = $config->get("pagination.per_page", 10);
$uploads = $config->get("storage.uploads_path", "/storage/uploads");

// ── CSV export of published posts ────────────────────────────
class PostExporter {
    public function __construct(private readonly PostRepository $repo) {}

    public function exportToCsv(): void {
        $posts    = $this->repo->findAllPublished(limit: 10000, offset: 0);
        $filename = "posts_" . date("Y-m-d") . ".csv";

        header("Content-Type: text/csv; charset=UTF-8");
        header("Content-Disposition: attachment; filename="$filename"");
        header("Cache-Control: no-store");

        $out = fopen("php://output", "wb");
        fwrite($out, "");   // BOM for Excel
        fputcsv($out, ["ID", "Title", "Slug", "Author", "Published At", "Views"]);

        foreach ($posts as $post) {
            fputcsv($out, [
                $post->id,
                $post->title,
                $post->slug,
                (string) $post->author,
                $post->getPublishedAt()?->format("Y-m-d H:i:s") ?? "",
                0,
            ]);
        }
        fclose($out);
        exit;
    }
}

// ── Media controller - secure file serving ───────────────────
class MediaController {
    private const UPLOAD_BASE = "/var/www/html/storage/uploads";
    private const ALLOWED_EXT = ["jpg", "jpeg", "png", "webp", "gif"];
    private const MIME_MAP    = [
        "jpg"  => "image/jpeg", "jpeg" => "image/jpeg",
        "png"  => "image/png",  "webp" => "image/webp",
        "gif"  => "image/gif",
    ];

    public function serve(string $filename): void {
        $filename  = basename($filename);   // no path traversal
        $ext       = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (!in_array($ext, self::ALLOWED_EXT, true)) {
            http_response_code(404); exit;
        }

        // Build path from segmented date dirs: uploads/2026/03/file.jpg
        $path = self::UPLOAD_BASE . "/" . $filename;
        if (!file_exists($path) || !is_file($path)) {
            http_response_code(404); exit;
        }

        // Verify it's really an image (not a PHP file with .jpg extension)
        if (!getimagesize($path)) {
            http_response_code(403); exit;
        }

        $mime   = self::MIME_MAP[$ext];
        $size   = filesize($path);
        $etag   = md5_file($path);
        $mtime  = filemtime($path);

        // ETag - return 304 if client has cached version
        if (isset($_SERVER["HTTP_IF_NONE_MATCH"]) && $_SERVER["HTTP_IF_NONE_MATCH"] === $etag) {
            http_response_code(304); exit;
        }

        header("Content-Type: $mime");
        header("Content-Length: $size");
        header("Cache-Control: public, max-age=31536000, immutable");
        header("ETag: $etag");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", $mtime) . " GMT");

        readfile($path);   // streams file without loading into RAM
        exit;
    }
}

Quick Quiz

Module Quiz

Module Quiz
Question 1 of 5

What is the purpose of the LOCK_EX flag in file_put_contents()?

Tip

Tip

Practice Mini Project Blog System Part 8 JSON Config CSV Export Media Upload in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Blog System - Part 8 (JSON Config, CSV Export & Media Upload)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Blog System Part 8 JSON Config CSV Export Media Upload from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Blog System Part 8 JSON Config CSV Export Media Upload is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/6 done