Rendering HTML with PHP Templates

8.Rendering HTML with PHP Templates

M

In this chapter

We'll learn how PHP renders HTML on the server — mixing PHP into HTML with short echo tags and the alternative syntax for if and foreach, escaping every value with htmlspecialchars() to stop XSS attacks, separating logic from templates with a small render() function, and building pages from layouts and partials — the ideas behind Blade and Twig.

16–18 min

The Problem in Real Life

A customer books under the name <b>Sam</b>, and the barbers' schedule turns bold from that line down. Marcus tries the name <script>alert('hi')</script> — and every barber who opens the schedule gets a pop-up. A real attacker's script could just as well send their session cookies somewhere else.

At the same time, the booking page has grown into 180 lines where SQL-like logic, ifs, echo "<div class=\"...\">" and form handling are tangled together, and nobody dares to change the layout.

M

We print whatever customers type straight into the page. Of course the browser runs it.

Mia

Echoing HTML Strings vs. Escaped Templates

XSS

Unescaped input becomes HTML — and script — in other people's browsers.

Templates

HTML files with small pieces of PHP, instead of HTML hidden in PHP strings.

Logic first, then the view

Decide everything in PHP code, then hand the data to a template that only displays it.

Rendering HTML with PHP Templates

PHP as a template language: PHP started as a way to put small pieces of code into HTML pages (Act 01), and it's still good at it. This chapter shows how to do it safely and cleanly:

  • PHP inside HTML: <?= ?> and the alternative syntax.
  • Escaping and XSS: htmlspecialchars() for every value.
  • Separating logic and templates: a small render() function.
  • Layouts and partials: reusing the page frame.
  • Server-side rendering: and template engines.

PHP inside HTML: in a template, HTML is the main content and PHP appears only where data goes in. <?= $value ?> is short for <?php echo $value; ?>. For control structures, PHP has an alternative syntax that reads better between HTML tags: <?php if ($errors): ?> … <?php endif; ?> and <?php foreach ($slots as $slot): ?> … <?php endforeach; ?> — the closing keyword says what's being closed, which } doesn't. A template should contain nothing more than these: values, conditions and loops.

A template: values, conditions and loops only
<?php
$customer = 'Sam Cole';
$slots = ['09:30', '16:00'];
$fullyBooked = false;
?>
<h1>Hello, <?= $customer ?></h1>
<?php if ($fullyBooked): ?>
<p>Sorry, Friday is fully booked.</p>
<?php else: ?>
<ul>
<?php foreach ($slots as $slot): ?>
<li><?= $slot ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

Escaping and XSS: when a template prints a value, the browser reads it as HTML. If the value contains <script>, the browser runs it — in the barber's browser, with the barber's cookies. That's cross-site scripting (XSS), one of the most common web vulnerabilities. The fix is to escape every value that isn't meant to be HTML: htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') turns < into &lt;, > into &gt;, & into &amp; and both kinds of quotes into entities, so the browser shows the characters instead of obeying them. ENT_QUOTES matters inside attributes like value="…". Wrap it in a short helper — e() — and use it for every <?= ?>. Escape at output, not when saving: the same name may later go into JSON, a CSV or an SMS, each with its own escaping.

XSS, and the escaped version
<?php
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$customer = "<script>alert('hi')</script>";
echo "<li>{$customer}</li>\n"; // the browser would RUN this
echo "<li>", e($customer), "</li>\n"; // the browser SHOWS this
echo '<input value="', e('Sam "The Blade" Cole'), '">', "\n"; // quotes are safe in attributes
// <li><script>alert('hi')</script></li>
// <li>&lt;script&gt;alert(&#039;hi&#039;)&lt;/script&gt;</li>
// <input value="Sam &quot;The Blade&quot; Cole">

Other contexts: HTML escaping protects HTML text and attribute values. Other places need other tools: a value inside a URL needs urlencode() (and must never start with javascript:), a value for JavaScript should go through json_encode() with JSON_HEX_TAG, and an href built from user input should be checked to start with / or https://. As a rule, keep user data out of <script> blocks and inline on…="" attributes altogether.

Table — Escaping by context
Where the value goesUseExample
HTML texthtmlspecialchars() / e()<p><?= e($customer) ?></p>
HTML attribute (quoted)htmlspecialchars() with ENT_QUOTES<input value="<?= e($customer) ?>">
URL query valueurlencode() — then e() for the HTML<a href="/slots.php?date=<?= e(urlencode($date)) ?>">
JavaScript datajson_encode(…, JSON_HEX_TAG | JSON_HEX_AMP)const slots = <?= json_encode($slots, JSON_HEX_TAG) ?>;
Trusted HTML you wroteNothing<?= $content ?> in the layout

Separating logic and templates: the tangled booking page mixed two jobs: deciding what to show (read the request, validate, load data, choose a status code) and showing it. Split them. The script does all the deciding first — which also makes headers and redirects possible (chapter 5) — and then calls render('booked', ['booking' => $booking]). render() makes the array's keys into variables with extract(), includes the template file inside ob_start() / ob_get_clean() to capture its HTML as a string, and outputs it. Templates live in their own folder, templates/, outside public/.

A render() function with a layout
<?php
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function renderString(string $template, array $data): string
{
extract($data); // ['booking' => …] becomes $booking
ob_start(); // capture the output instead of sending it
eval('?>' . $template); // real code: require "templates/{$name}.php";
return ob_get_clean();
}
$page = <<<'TPL'
<p>Thanks, <?= e($booking['customer']) ?>. Booking #<?= $booking['id'] ?> is at <?= e($booking['slot']) ?>.</p>
TPL;
$layout = <<<'TPL'
<html><head><title><?= e($title) ?></title></head><body>
<?= $content ?>
</body></html>
TPL;
$booking = ['id' => 4811, 'customer' => 'Sam <b>Cole</b>', 'slot' => '2026-11-07 16:00'];
$content = renderString($page, ['booking' => $booking]);
echo renderString($layout, ['title' => 'Booked', 'content' => $content]);
// <html><head><title>Booked</title></head><body>
// <p>Thanks, Sam &lt;b&gt;Cole&lt;/b&gt;. Booking #4811 is at 2026-11-07 16:00.</p></body></html>

Layouts and partials: every page shares the same frame — <head>, logo, menu, footer. Put it in one layout template with a $content placeholder; render() renders the page template first, then the layout around it. Repeated pieces, like a booking card used on three pages, become partials: small templates included with <?php require __DIR__ . '/partials/booking-card.php'; ?>. The diagram below shows how a page is assembled.

How booked.php builds its page

public/booked.php

reads ?id, loads booking 4811, chooses 200 or 404 — no HTML

then

render('booked', ['booking' => …])

extract() + ob_start()

1. the page

templates/booked.php

<p>Thanks, <?= e($booking['customer']) ?>…</p> → $content

2. the frame around it

templates/layout.php

<html><head>…</head><body><?= $content ?></body></html>

Server-side rendering and template engines: building the complete HTML on the server like this is server-side rendering: the browser receives a finished page, which is fast to display and easy for search engines to read. The alternative is client-side rendering, where JavaScript fetches JSON (chapter 9) and builds the page in the browser; many apps mix both. Dedicated template engines — Blade in Laravel, Twig in Symfony — add a shorter syntax ({{ $name }}) and, most importantly, escape automatically, so forgetting e() is impossible. Under the hood, Blade compiles templates into exactly the kind of PHP shown here.

The same template in Blade (Laravel) — escaped automatically
{{-- resources/views/booked.blade.php --}}
@extends('layout')
@section('content')
<p>Thanks, {{ $booking->customer }}. Booking #{{ $booking->id }} is at {{ $booking->slot }}.</p>
@foreach ($slots as $slot)
<li>{{ $slot }}</li>
@endforeach
@endsection

Key Takeaway

Templates are HTML with small pieces of PHP: <?= ?> for values and the alternative syntax (if: … endif;, foreach: … endforeach;) for structure — nothing else. Every value printed into HTML must be escaped with htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') (an e() helper) or user input becomes markup and script — XSS; escape at output, and use urlencode()/json_encode() for URL and JavaScript contexts. Do all logic first, then render(): extract() the data, include the template inside ob_start()/ob_get_clean(), and wrap it in a layout; reuse pieces as partials. That's server-side rendering, and Blade/Twig do the same with automatic escaping.

Why This Matters

XSS is in the OWASP Top 10 year after year, and it almost always comes from one missing escape. Escaping every value by habit — or using an engine that does it for you — removes the whole class of bugs.

Separating logic from templates is the "view" in MVC, the structure of Laravel and every major framework. The render() function in this chapter is a ten-line version of what Blade and Twig do.

Every value on BookBay's pages goes through e(), the pages are templates inside one layout, and <b>Sam</b> is displayed as text. Next, the partner building the mobile app needs more than HTML: free slots, new bookings and cancellations, as JSON, with proper status codes and error messages. That's the next chapter: building JSON APIs.