HTML Integration with PHP
By the end of this lesson you will be able to build a small template layer in plain PHP: views and a layout joined with output buffering, escaping helpers for text, attributes and URLs, form fields that keep their values and show accessible errors, CSRF tokens, flash messages after a redirect, a fresh CSP nonce on every response and caching headers that fit each kind of page.
What you should know first: HTML with PHP & MySQL (the e() helper, shared header and footer, PDO, a first sticky form), Secure Form Handling, Content Security Policy (CSP) and JSON-LD Integration. On the PHP side, Sessions & Cookies and A Simple MVC Router help. Everything here was run on PHP 8.4 with its built-in server.
Why header.php and footer.php stop being enough
The require 'header.php' style from lesson 112 prints the top of the page before the page itself runs. On a bigger site that causes three problems:
- Headers come too late. Status codes, redirects, cookies and the CSP header must be sent before any HTML. Once the header file has printed, they fail with "headers already sent".
- The head cannot know what the page needs. A product page wants JSON-LD, a meta description and a canonical link, but the
<head>was printed before the product was loaded. - Errors leave half a page. If the database fails in the middle, the visitor gets a broken page with status 200.
The fix is to build the whole page as a string first, then send headers and HTML together. Think of a Mumbai dabbawala: the cook fills the containers (the view), packs them into the carrier (the layout), and only a complete carrier leaves the kitchen.
app/helpers.php escaping, View class, CSRF, flash, nonce, send_html()
views/layout.php the page shell
views/book.php one view per page
views/enquiry.php
public/book.php small controllers: load data, call page()
public/enquiry.phpStep 1: render views into strings
Output buffering tells PHP to collect printed output in memory instead of sending it. ob_start() starts a buffer and ob_get_clean() returns its text and closes it.
final class View
{
public static function render(string $view, array $data = []): string
{
$file = __DIR__ . '/../views/' . $view . '.php';
$level = ob_get_level();
ob_start();
try {
(static function (string $__file, array $__data): void {
extract($__data, EXTR_SKIP);
require $__file;
})($file, $data);
return (string) ob_get_clean();
} catch (Throwable $error) {
while (ob_get_level() > $level) {
ob_end_clean(); // throw away the half-built page
}
throw $error;
}
}
}
function page(string $view, array $data, int $status = 200, bool $cacheable = false): void
{
$content = View::render($view, $data); // 1. the view first
$html = View::render('layout', $data + ['content' => $content]); // 2. then the layout
send_html($html, $status, $cacheable); // 3. headers, then body
}extract()turns['book' => ...]into a$bookvariable inside the view.EXTR_SKIPstops data from overwriting$__file.- The static closure gives the view a clean scope, apart from
render()'s own variables. - On an exception, the
catchblock empties every buffer it opened, so no half page escapes.
The view is rendered before the layout. That order is the whole trick, as the next step shows.
Step 2: stacks let a view fill the head
Add a stack: named slots that views push HTML into and the layout prints later. This is the same idea as @push and @stack in Laravel's Blade.
// inside class View
private static array $open = [];
private static array $stacks = [];
public static function push(string $stack): void
{
self::$open[] = $stack;
ob_start();
}
public static function end(): void
{
$stack = array_pop(self::$open);
self::$stacks[$stack][] = (string) ob_get_clean();
}
public static function stack(string $stack): string
{
return implode('', self::$stacks[$stack] ?? []);
}The layout prints the stacks and the view's content:
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($title) ?> | Kochi Book House</title>
<?= View::stack('head') ?>
</head>
<body>
<header><a href="/">Kochi Book House</a></header>
<main>
<?php if (!empty($flash)): ?>
<p role="status" class="flash"><?= e($flash) ?></p>
<?php endif; ?>
<?= $content ?>
</main>
<?= View::stack('scripts') ?>
</body>
</html><?= $content ?> is the only value printed without e(). It is HTML that our own view built, with every value inside already escaped. Escaping it again would show tags as text.
The book view pushes its SEO tags, then prints the body. It uses the helpers from the next section:
<?php View::push('head'); ?>
<meta name="description" content="<?= e($book['blurb']) ?>">
<link rel="canonical" href="<?= e($book['url']) ?>">
<script type="application/ld+json"><?= json_encode([
'@context' => 'https://schema.org',
'@type' => 'Book',
'name' => $book['title'],
'author' => ['@type' => 'Person', 'name' => $book['author']],
'offers' => ['@type' => 'Offer', 'price' => $book['price'], 'priceCurrency' => 'INR'],
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_THROW_ON_ERROR) ?></script>
<?php View::end(); ?>
<h1><?= e($book['title']) ?></h1>
<p>By <?= e($book['author']) ?>, ₹<?= e($book['price']) ?></p>
<p><a href="<?= e(url('/search', ['author' => $book['author'], 'sort' => 'new'])) ?>">More by this author</a></p>
<p><a<?= attrs(['href' => safe_href($book['sellerSite']), 'rel' => 'nofollow ugc']) ?>>Seller's website</a></p>The seller had typed javascript:alert("hi") as their website. With php -S localhost:8000 -t public running, curl http://localhost:8000/book.php returned:
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chemmeen | Kochi Book House</title>
<meta name="description" content="A "classic" love story from the Kerala coast.">
<link rel="canonical" href="https://books.example.in/books/chemmeen">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"Book","name":"Chemmeen","author":{"@type":"Person","name":"Thakazhi Sivasankara Pillai"},"offers":{"@type":"Offer","price":"299.00","priceCurrency":"INR"}}</script>
</head>
<body>
<header><a href="/">Kochi Book House</a></header>
<main>
<h1>Chemmeen</h1>
<p>By Thakazhi Sivasankara Pillai, ₹299.00</p>
<p><a href="/search?author=Thakazhi%20Sivasankara%20Pillai&sort=new">More by this author</a></p>
<p><a href="#" rel="nofollow ugc">Seller's website</a></p>
</main>
</body>
</html>The JSON-LD uses the flags explained in the JSON-LD lesson; JSON_HEX_TAG is the one that stops a </script> inside data from closing the block.
Escaping helpers for each context
e() from lesson 112 handles text and quoted attributes. Three small helpers cover the other common places:
function attrs(array $attributes): string
{
$html = '';
foreach ($attributes as $name => $value) {
if ($value === null || $value === false) {
continue; // leave the attribute out
}
if ($value === true) {
$html .= ' ' . $name; // boolean attribute: required, disabled
continue;
}
$html .= ' ' . $name . '="' . e($value) . '"';
}
return $html;
}
function url(string $path, array $query = []): string
{
$qs = http_build_query($query, '', '&', PHP_QUERY_RFC3986);
return $qs === '' ? $path : $path . '?' . $qs;
}
function safe_href(string $link): string
{
$scheme = strtolower((string) parse_url($link, PHP_URL_SCHEME));
return in_array($scheme, ['http', 'https'], true) ? $link : '#';
}Testing them in the terminal:
<input name="student" value="Meera "Mini" Nair" required> /search?q=R%26D%20books&city=Kochi <a href="/search?q=R%26D%20books&city=Kochi">Search</a> https://meera.example.in -> https://meera.example.in JavaScript:alert(1) -> # javascript:alert(1) -> # data:text/html,<b>x</b> -> #
attrs()writesrequiredfortrueand dropsdisabledforfalse. Attribute names are not escaped, so they must come from your code, never from users.url()encodes each value once, so&inside "R&D" cannot start a new parameter. Thene()turns the separator&into&for the HTML.safe_href()is an allow-list: onlyhttpandhttpspass. A deny-list misses tricks like the leading space.
Step 3: a form helper with sticky values and errors
Hand-writing label, value, error and ARIA links for every field invites mistakes. One function writes them the same way every time:
function field(string $name, string $label, array $old, array $errors, array $extra = []): string
{
$id = 'f-' . $name;
$error = $errors[$name] ?? null;
$html = '<p><label for="' . $id . '">' . e($label) . '</label> <input' . attrs([
'id' => $id,
'name' => $name,
'value' => $old[$name] ?? '',
'aria-invalid' => $error ? 'true' : null,
'aria-describedby' => $error ? $id . '-error' : null,
] + $extra) . '>';
if ($error) {
$html .= ' <span id="' . $id . '-error" class="error">' . e($error) . '</span>';
}
return $html . '</p>';
}The controller for a bulk-order form checks the CSRF token, validates, and either shows errors or redirects. The csrf_ok() helper is the hash_equals() check from Secure Form Handling, and csrf_field() prints the hidden input:
<?php
declare(strict_types=1);
require __DIR__ . '/../app/helpers.php';
session_start(['cookie_httponly' => true, 'cookie_samesite' => 'Lax', 'use_strict_mode' => true]);
$old = ['school' => '', 'phone' => '', 'copies' => ''];
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!csrf_ok()) {
send_html('<p>Your session expired. Please reload the form.</p>', 403);
exit;
}
foreach ($old as $key => $_) {
$value = $_POST[$key] ?? '';
$old[$key] = is_string($value) ? trim($value) : '';
}
if ($old['school'] === '') {
$errors['school'] = 'Enter the school name.';
}
if (!preg_match('/^[6-9][0-9]{9}$/', $old['phone'])) {
$errors['phone'] = 'Enter a 10-digit mobile number.';
}
if (filter_var($old['copies'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 10]]) === false) {
$errors['copies'] = 'Order at least 10 copies.';
}
if ($errors === []) {
// save with a prepared INSERT here
flash("Thank you. We will call {$old['school']} on {$old['phone']}.");
header('Location: /enquiry.php', true, 303); // Post/Redirect/Get
exit;
}
}
page('enquiry', [
'title' => 'Bulk order',
'old' => $old,
'errors' => $errors,
'flash' => take_flash(),
], $errors ? 422 : 200);The view prints an error summary when there are errors, then <?= field('phone', 'Mobile number', $old, $errors, ['type' => 'tel', 'autocomplete' => 'tel', 'required' => true]) ?> for each field. It pushes one small script that moves focus to the summary. Posting St. Teresa's "Convent", Kochi, phone 98470 and 4 copies returned status 422 and this page:
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bulk order | Kochi Book House</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 36rem; }
label { display: block; font-weight: bold; }
input { padding: 6px; inline-size: 18rem; max-inline-size: 100%; }
[aria-invalid="true"] { border: 2px solid #b00020; }
.error { display: block; color: #b00020; }
#error-summary { border: 3px solid #b00020; padding: 4px 12px; }
#error-summary:focus { outline: 3px solid #1d4ed8; }
</style>
</head>
<body>
<header><a href="/">Kochi Book House</a></header>
<main>
<div id="error-summary" role="alert" tabindex="-1">
<h2>Please fix 2 problems</h2>
<ul>
<li><a href="#f-phone">Enter a 10-digit mobile number.</a></li>
<li><a href="#f-copies">Order at least 10 copies.</a></li>
</ul>
</div>
<h1>Bulk order for schools</h1>
<form method="post" action="/enquiry.php" novalidate>
<input type="hidden" name="_token" value="23258c6270ac2068ca96a63868cb02a82121c8b66dbeccf92b3c0e9e7458e6e1">
<p><label for="f-school">School name</label> <input id="f-school" name="school" value="St. Teresa's "Convent", Kochi" autocomplete="organization" required></p>
<p><label for="f-phone">Mobile number</label> <input id="f-phone" name="phone" value="98470" aria-invalid="true" aria-describedby="f-phone-error" type="tel" autocomplete="tel" required> <span id="f-phone-error" class="error">Enter a 10-digit mobile number.</span></p>
<p><label for="f-copies">Number of copies</label> <input id="f-copies" name="copies" value="4" aria-invalid="true" aria-describedby="f-copies-error" type="number" min="10" required> <span id="f-copies-error" class="error">Order at least 10 copies.</span></p>
<button type="submit">Send enquiry</button>
</form>
</main>
<script nonce="0ERlEH9TozXwhK6wVunSPQ==">
document.getElementById("error-summary")?.focus();
</script>
</body>
</html>The summary has focus when the page loads, so keyboard and screen reader users start at the problems. Click "Order at least 10 copies": focus jumps to that field, and its error is read with it. The school name kept both quote marks, safely escaped.
Step 4: Post/Redirect/Get with a flash message
Errors re-render the page directly with status 422, so the typed values are still in $old and nothing extra goes into the session. Success is different. A valid POST answers with a 303 redirect, and the thank-you text travels in the session as a flash message: a value read once, then deleted.
function flash(string $message): void
{
$_SESSION['flash'] = $message;
}
function take_flash(): ?string
{
$message = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']); // show it once only
return $message;
}Test it with curl and a cookie file ($TOKEN holds the token copied from the form). First a valid POST, then the same GET twice:
curl -si -b jar.txt -c jar.txt -d "_token=$TOKEN&school=Sacred+Heart+School&phone=9847012345&copies=40" http://localhost:8000/enquiry.php | grep -E "^(HTTP|Location)"
curl -s -b jar.txt http://localhost:8000/enquiry.php | grep flash
curl -s -b jar.txt http://localhost:8000/enquiry.php | grep flashHTTP/1.1 303 See Other
Location: /enquiry.php
<p role="status" class="flash">Thank you. We will call Sacred Heart School on 9847012345.</p>The second GET printed nothing: the message was shown once and deleted. Pressing Refresh repeats only the GET, so no second order is created. The layout escapes the flash text, because it contains what the visitor typed. A POST with a guessed token got HTTP/1.1 403 Forbidden. (PHP's built-in development server labels 422 as "Unknown Status Code". Only the number matters to browsers.)
A fresh CSP nonce for every response
In a template layer, two rules matter: one nonce per response, shared by every script tag, and the header sent after the page is built:
function csp_nonce(): string
{
return $GLOBALS['csp_nonce'] ??= base64_encode(random_bytes(16));
}
// inside send_html(), before any output
$nonce = $GLOBALS['csp_nonce'] ?? null;
$scripts = $nonce ? "'nonce-{$nonce}' 'strict-dynamic'" : "'self'";
header("Content-Security-Policy: script-src {$scripts}; object-src 'none'; base-uri 'none'");A view asks for the nonce with <script nonce="<?= e(csp_nonce()) ?>">, inside View::push('scripts'). Pages without inline scripts never create one and get script-src 'self'. Two requests in a row:
curl -sI http://localhost:8000/enquiry.php | grep -i "^content-security"
curl -sI http://localhost:8000/enquiry.php | grep -i "^content-security"Content-Security-Policy: script-src 'nonce-96UtlwDtEQblpOV29iX3sw==' 'strict-dynamic'; object-src 'none'; base-uri 'none' Content-Security-Policy: script-src 'nonce-Ov5p4SWoJS9c9SCmNkfleg==' 'strict-dynamic'; object-src 'none'; base-uri 'none'
Here is a page as the browser receives it. The policy is in a <meta> tag so the editor can apply it, and a review was printed raw by mistake:
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-zCjgr/9IgVgD6bl/Xa1W1A=='">
<title>Reviews | Kochi Book House</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
.flash { background: #e8f5e9; padding: 8px; }
</style>
</head>
<body>
<main>
<p role="status" class="flash">Thank you. Your review was saved.</p>
<h1>Reviews of Chemmeen</h1>
<p>Kabir: Loved it! <script>document.title = "Hacked"; document.body.style.background = "red";</script></p>
<p id="check">Waiting for the page script...</p>
</main>
<script nonce="zCjgr/9IgVgD6bl/Xa1W1A==">
document.querySelector("#check").textContent =
"Page script ran. Tab title is still: " + document.title;
</script>
</body>
</html>The page script runs because its nonce matches. Kabir's injected script has no nonce, so it is blocked: the background stays white and the console reports a CSP violation. The nonce is a second wall; the real fix is still e().
Caching headers for HTML
Caching means a browser or proxy keeps a copy of a response to reuse later. HTML needs different rules from images:
| Page | Header | Why |
|---|---|---|
| Anything with a session, form token or nonce | Cache-Control: no-store | Personal data, and a reused nonce is useless |
| Public page, such as a book | Cache-Control: no-cache plus ETag | Keep a copy, but ask the server each time |
| Hashed CSS and JS files | Cache-Control: max-age=31536000, immutable | Set in the web server, not in PHP |
no-cache means "check with the server before reuse". An ETag is a fingerprint of the response. send_html() hashes the finished HTML with hash('xxh128', $html). If the browser sends that fingerprint back in If-None-Match, PHP answers 304 Not Modified with no body:
curl -si -H 'If-None-Match: "e3c24ac62456abd25ba90797311251c0"' http://localhost:8000/book.phpHTTP/1.1 304 Not Modified Host: localhost:8000 Date: Sun, 15 Nov 2026 15:48:20 GMT Connection: close X-Powered-By: PHP/8.4.27 Content-Type: text/html; charset=utf-8 Content-Security-Policy: script-src 'self'; object-src 'none'; base-uri 'none' Cache-Control: no-cache ETag: "e3c24ac62456abd25ba90797311251c0"
The page was still built, but no body was sent, which saves data on slow mobile connections. Note that session_start() adds Expires: Thu, 19 Nov 1981... and no-store headers by itself (the session.cache_limiter setting), so never start a session on pages you want cached.
Common mistakes
- Escaping
$contentin the layout. The view's HTML then appears as text. - Echoing before
header(). With a template layer, onlysend_html()prints. - Redirecting with 302 after a POST. Use 303, which always makes the next request a GET.
- One nonce per deployment. A nonce must be new on every response.
Interview questions
1. Why render the view before the layout?
The view may need to add things to the head, such as JSON-LD or a canonical link, and it may decide the status code. Rendering it first into a buffer collects those pushes before the layout prints the head. Headers can also still be sent, because nothing has reached the browser.
2. What does ob_get_clean() do, and why clean buffers on an exception?
It returns the buffered output as a string and closes the buffer. If a view throws halfway, the open buffers hold a partial page. Closing them with ob_end_clean() means the error handler can send a clean error page with the correct status.
3. Why answer a failed form with 422 but a successful one with 303?
A failed form must show the typed values and errors, so rendering directly is simplest, and 422 tells clients that the input was invalid. A successful POST should not be repeatable by Refresh, so a 303 redirect turns the next request into a GET, and a flash message carries the confirmation.
4. How do you generate a CSP nonce in PHP, and where do you use it?
Create it once per response with base64_encode(random_bytes(16)), put it in the Content-Security-Policy header and in the nonce attribute of each allowed <script>. The header must be sent before output, which a buffered template layer makes easy.
5. What is the difference between no-cache and no-store?
no-store forbids keeping any copy, which suits personal pages. no-cache allows a copy but requires checking with the server first, usually through ETag and If-None-Match, which can return a small 304 Not Modified.
Key points
- Render the view into a string with output buffering, then wrap it in the layout, then send headers and HTML together.
- Stacks let a view push meta tags, JSON-LD and scripts into the layout;
<?= $content ?>is the only raw print. - Use
e()for text and attributes,attrs()for attribute lists,url()for query strings and an allow-list for user URLs. - One
field()helper writes label, sticky value, error text,aria-invalidandaria-describedbythe same way every time. - Check the CSRF token first, answer invalid input with 422, and redirect success with 303 plus a flash message read once.
- Make a new nonce per response; never cache nonce or session pages, and use
ETagwithno-cachefor public HTML.
Exercise
Add an "Edit review" page to the Kochi Book House template layer. The controller starts a session, shows a form with a rating field (number, 1 to 5) and a review field (required, up to 500 characters), and keeps the typed values after an error. Use field() for the rating and write the <textarea> markup yourself with the same ARIA pattern. On success, flash "Review updated" and redirect with 303. Push a nonce script that counts the characters left in the review box.
Show solution
<?php
// public/review.php
declare(strict_types=1);
require __DIR__ . '/../app/helpers.php';
session_start(['cookie_httponly' => true, 'cookie_samesite' => 'Lax', 'use_strict_mode' => true]);
$old = ['rating' => '5', 'review' => ''];
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!csrf_ok()) {
send_html('<p>Your session expired. Please reload the form.</p>', 403);
exit;
}
foreach ($old as $key => $_) {
$value = $_POST[$key] ?? '';
$old[$key] = is_string($value) ? trim($value) : '';
}
if (filter_var($old['rating'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 5]]) === false) {
$errors['rating'] = 'Choose a rating from 1 to 5.';
}
if ($old['review'] === '' || mb_strlen($old['review']) > 500) {
$errors['review'] = 'Write a review of up to 500 characters.';
}
if ($errors === []) {
flash('Review updated.');
header('Location: /review.php', true, 303);
exit;
}
}
page('review', ['title' => 'Edit review', 'old' => $old, 'errors' => $errors, 'flash' => take_flash()], $errors ? 422 : 200);<!-- views/review.php -->
<h1>Edit your review</h1>
<form method="post" action="/review.php">
<?= csrf_field() ?>
<?= field('rating', 'Rating (1 to 5)', $old, $errors, ['type' => 'number', 'min' => 1, 'max' => 5, 'required' => true]) ?>
<p>
<label for="f-review">Review</label>
<textarea<?= attrs([
'id' => 'f-review', 'name' => 'review', 'maxlength' => 500, 'required' => true,
'aria-invalid' => isset($errors['review']) ? 'true' : null,
'aria-describedby' => isset($errors['review']) ? 'f-review-error left' : 'left',
]) ?>><?= e($old['review']) ?></textarea>
<span id="left"></span>
<?php if (isset($errors['review'])): ?>
<span id="f-review-error" class="error"><?= e($errors['review']) ?></span>
<?php endif; ?>
</p>
<button type="submit">Save review</button>
</form>
<?php View::push('scripts'); ?>
<script nonce="<?= e(csp_nonce()) ?>">
const box = document.getElementById("f-review");
const left = document.getElementById("left");
const update = () => { left.textContent = (500 - box.value.length) + " characters left"; };
box.addEventListener("input", update);
update();
</script>
<?php View::end(); ?>A <textarea> keeps its value between the tags, not in a value attribute, so it is escaped with e() there. Because the page uses a session and a nonce, send_html() sends Cache-Control: no-store.
Quick Quiz
1. Why does page() render the view before the layout?
Rendering the view first collects its stacks and keeps the headers unsent until the end.
2. Which status should a successful form POST answer with in Post/Redirect/Get?
303 tells the browser to load the next page with GET, so Refresh cannot repeat the POST.
3. What does safe_href('javascript:alert(1)') return in this lesson?
Only http and https links pass the allow-list.
4. A public book page sends Cache-Control: no-cache and an ETag. What happens on the next visit?
no-cache means revalidate before reuse; the ETag makes that check cheap.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
