Lesson 4 of 6
Output Buffering & HTTP Performance Headers
Output buffering lets you accumulate PHP output before sending it - then compress it with gzip, set Content-Length, and send it as one HTTP response. HTTP cache headers (Cache-Control, ETag, Last-Modified) allow browsers and CDNs to cache responses, reducing server load dramatically.
Output Buffering, gzip & HTTP Cache Headers
<?php
declare(strict_types=1);
// ── Output buffering ──────────────────────────────────────────
ob_start(); // Start capturing output
// All echo/print/include goes into buffer - nothing sent to browser yet
echo "<html><body>";
echo "<h1>Blog</h1>";
include "views/posts.php";
echo "</body></html>";
$html = ob_get_clean(); // Get captured output and turn off buffering
// Compress if client supports gzip
if (str_contains($_SERVER["HTTP_ACCEPT_ENCODING"] ?? "", "gzip")) {
$compressed = gzencode($html, 6); // level 6 = good balance speed/size
header("Content-Encoding: gzip");
header("Content-Length: " . strlen($compressed));
echo $compressed;
} else {
header("Content-Length: " . strlen($html));
echo $html;
}
// ── HTTP cache headers ─────────────────────────────────────────
// Static assets (images, fonts, CSS, JS) - long cache, immutable
// Only send once per deploy (cache-busted by changing filename)
header("Cache-Control: public, max-age=31536000, immutable");
// API responses - no cache (each request gets fresh data)
header("Cache-Control: no-store");
// HTML pages - cache in browser, revalidate with server
// Browser uses cached copy until max-age expires, then asks server
header("Cache-Control: public, max-age=600, must-revalidate"); // 10 min
// ── ETag (Entity Tag) - conditional requests ──────────────────
function sendWithEtag(string $content): void {
$etag = '"' . md5($content) . '"'; // ETag must be quoted string
// Check if client already has this version
$clientEtag = $_SERVER["HTTP_IF_NONE_MATCH"] ?? "";
if ($clientEtag === $etag) {
http_response_code(304); // Not Modified - send no body
exit;
}
header("ETag: $etag");
header("Cache-Control: public, max-age=600, must-revalidate");
echo $content;
}
// ── Last-Modified - conditional request ───────────────────────
function sendWithLastModified(string $content, DateTimeImmutable $lastModified): void {
$modifiedStr = gmdate("D, d M Y H:i:s", $lastModified->getTimestamp()) . " GMT";
$clientMod = $_SERVER["HTTP_IF_MODIFIED_SINCE"] ?? "";
if ($clientMod === $modifiedStr) {
http_response_code(304); exit;
}
header("Last-Modified: $modifiedStr");
header("Cache-Control: public, max-age=600");
echo $content;
}
// ── Range requests - for file downloads / video streaming ─────
function sendFileWithRangeSupport(string $filePath): void {
$size = filesize($filePath);
header("Accept-Ranges: bytes");
if (isset($_SERVER["HTTP_RANGE"])) {
[$start, $end] = sscanf($_SERVER["HTTP_RANGE"], "bytes=%d-%d");
$end = $end ?? $size - 1;
$length = $end - $start + 1;
http_response_code(206);
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
$fh = fopen($filePath, "rb");
fseek($fh, $start);
echo fread($fh, $length);
fclose($fh);
} else {
header("Content-Length: $size");
readfile($filePath);
}
}Quick Quiz
Tip
Tip
Practice Output Buffering HTTP Performance Headers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Output Buffering & HTTP Performance Headers
Practice Task
Note
Practice Task - (1) Write a working example of Output Buffering HTTP Performance Headers 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 Output Buffering HTTP Performance Headers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?