Input Handling and Output Escaping

Input Handling and Output Escaping in PHP: --- A shipping depot has two very different docks, and confusing them is where trouble starts.


The Analogy: The Shipping Depot's Receiving and Dispatch Docks

A shipping depot has two very different docks, and confusing them is where trouble starts. At the receiving dock, every incoming crate is inspected against a checklist: is it the declared goods, is it within weight, is the paperwork present. Anything failing is refused at the door. At the dispatch dock, goods leaving the depot are packed differently depending on where they are going -- a fragile item to a customer is wrapped one way, the same item loaded onto a sea container is wrapped another, and an item handed to a courier gets a third packaging. Input handling is the receiving dock; output escaping is the dispatch dock. They are separate jobs at separate ends of the building.

At receiving, the rule is validate then reject: check the goods conform, and turn away what does not. This is input validation -- confirming an email looks like an email, an age is a number in range, a required field is present -- performed the moment data arrives, before it is stored or used. Crucially, the depot does not repackage incoming goods to "make them safe"; it verifies them. Trying to sanitise your way to safety at the input dock is like sanding the corners off a crate that failed inspection: you have altered the goods and still not established they are what they claim to be.

At dispatch, the rule is package for the destination. The identical stored item is wrapped one way for an HTML page, another for a URL, another for a database query, another for a JavaScript block. The wrapping -- the escaping -- depends entirely on where the value is going, because each destination has different characters that are dangerous in that context. A quote is harmless in a URL but breaks out of an HTML attribute; an angle bracket is fine in a database value but injects script into HTML. So you store the value once, raw, and escape it correctly at each point of output.

The failure mode is the depot that escapes at the wrong dock, or wraps for the wrong destination. A depot that "sanitises" everything at receiving -- stripping characters from incoming data -- corrupts legitimate content (a customer really is named O'Brien) while providing no guarantee for output, because a value safe for HTML is still dangerous in a URL. And a depot that packs an HTML-wrapped item into a database, or a database-escaped item into a web page, protects against nothing while double-mangling the data. The discipline is precise: validate at input, store raw, and escape at output for the specific context -- getting the dock or the destination wrong is how both bugs and vulnerabilities are born.


Syntax or Core Structure

Input handling starts with validation, and PHP's filter_var provides ready-made validators. It returns the validated value or false, cleanly separating good input from bad.

<?php
declare(strict_types=1);

$emails = ['ada@example.com', 'not-an-email', 'ben@site.org'];
foreach ($emails as $e) {
    $valid = filter_var($e, FILTER_VALIDATE_EMAIL);
    echo $e, ' -> ', ($valid === false ? 'invalid' : 'valid'), "\n";
}

$ints = ['42', '3.14', 'x', '-7'];
foreach ($ints as $s) {
    $n = filter_var($s, FILTER_VALIDATE_INT);
    echo $s, ' -> ', ($n === false ? 'not int' : "int $n"), "\n";
}

Output:

ada@example.com -> valid
not-an-email -> invalid
ben@site.org -> valid
42 -> int 42
3.14 -> not int
x -> not int
-7 -> int -7

FILTER_VALIDATE_EMAIL accepts the two well-formed addresses and rejects the plain string. FILTER_VALIDATE_INT accepts 42 and -7 as integers but rejects 3.14 (not an integer) and x (not a number). Returning false for bad input gives you a clear, checkable signal at the receiving dock, before the value goes any further into the system.

Validating with options

filter_var accepts an options array to tighten validation -- enforcing an integer range, for instance -- and offers validators for URLs, IP addresses, and more. This lets the receiving dock reject not just malformed values but out-of-bounds ones.

<?php
declare(strict_types=1);

function inRange(string $s, int $min, int $max): string {
    $n = filter_var($s, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => $min, 'max_range' => $max],
    ]);
    return $n === false ? 'out of range' : "ok: $n";
}

echo inRange('50', 1, 100), "\n";
echo inRange('0', 1, 100), "\n";
echo inRange('250', 1, 100), "\n";

foreach (['https://example.com', 'not a url', 'ftp://host/f'] as $u) {
    $ok = filter_var($u, FILTER_VALIDATE_URL);
    echo $u, ' -> ', ($ok === false ? 'invalid url' : 'valid url'), "\n";
}

Output:

ok: 50
out of range
out of range
https://example.com -> valid url
not a url -> invalid url
ftp://host/f -> valid url

The range check accepts 50 but rejects both 0 (below the minimum) and 250 (above the maximum), enforcing bounds as well as type. FILTER_VALIDATE_URL accepts the HTTPS and FTP URLs and rejects the plain text -- though note it validates syntax only, not that the scheme is one you want, so you would still whitelist allowed schemes yourself. Validating type, range, and format together at the boundary keeps malformed and out-of-bounds values out from the start.


Technical Depth: Escaping Per Context

Each destination needs its own escaping

There is no single "escape" function. The correct escaping depends entirely on the context the value lands in, because each context has different dangerous characters.

ContextFunctionNeutralises
HTML body / attributehtmlspecialchars (ENT_QUOTES)< > & " '
URL queryrawurlencodespaces, & ? #, etc.
SQLprepared statements (bind)quotes, injection
JavaScript / JSONjson_encode (safe flags)< > " and unicode
<?php
declare(strict_types=1);

$userInput = '"><script>alert(1)</script>';

echo 'html: ', htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8'), "\n";

$name = 'Ada & Ben';
echo 'url: /search?q=', rawurlencode($name), "\n";

echo 'js: ', json_encode($userInput, JSON_HEX_TAG | JSON_HEX_QUOT), "\n";

Output:

html: &quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;
url: /search?q=Ada%20%26%20Ben
js: "\u0022\u003E\u003Cscript\u003Ealert(1)\u003C\/script\u003E"

The same script payload is neutralised three different ways. htmlspecialchars with ENT_QUOTES converts the angle brackets and quotes to entities for HTML. rawurlencode percent-encodes the space and ampersand for a URL query. json_encode with JSON_HEX_TAG and JSON_HEX_QUOT escapes the tag and quote characters to unicode so the value is safe inside a script block. Using the wrong one -- HTML-escaping a URL parameter, say -- protects against nothing in the actual context.

Store raw, escape at output

Because escaping is context-dependent, you must not escape at input and store the escaped form. Store the raw value; escape it at each point of output.

<?php
declare(strict_types=1);

$stored = "O'Brien <team@co> & co";

echo 'html: ', htmlspecialchars($stored, ENT_QUOTES, 'UTF-8'), "\n";
echo 'url:  ', rawurlencode($stored), "\n";
echo "sql:  SELECT * FROM t WHERE name = ?  -- bind: ", $stored, "\n";

Output:

html: O&#039;Brien &lt;team@co&gt; &amp; co
url:  O%27Brien%20%3Cteam%40co%3E%20%26%20co
sql:  SELECT * FROM t WHERE name = ?  -- bind: O'Brien <team@co> & co

The one stored value O'Brien <team@co> & co is escaped three ways from a single raw source. For HTML the apostrophe, brackets, and ampersand become entities; for the URL every special character is percent-encoded; for SQL the value is not escaped at all but passed as a bound parameter to a ? placeholder. Had you escaped at input -- storing the HTML-entity version -- the URL and SQL uses would be wrong, and the stored data would be corrupted for any non-HTML consumer. Raw storage plus output escaping is the only approach that serves every context correctly. This is also why modern template engines escape automatically on output rather than expecting pre-escaped data: the engine knows the context it is rendering into, so it can apply the right escaping at the last possible moment, and it can only do that correctly if the value it receives is still raw. Pre-escaping upstream both double-escapes in the engine and prevents any other consumer from getting a clean value.


Real World Example: A Comment Box That Validates and Escapes

A comment box shows both docks at work: validate on the way in (reject empty or over-long comments), store raw, and escape on the way out for HTML. The XSS payload is stored verbatim but rendered harmless.

<?php
declare(strict_types=1);

final class CommentBox {
    /** @var array<int,array{author:string,body:string}> */
    private array $comments = [];

    public function add(string $author, string $body): string {
        $author = trim($author);
        $body = trim($body);
        if ($author === '' || $body === '') {
            return 'rejected: empty field';
        }
        if (mb_strlen($body) > 200) {
            return 'rejected: too long';
        }
        $this->comments[] = ['author' => $author, 'body' => $body];
        return 'accepted';
    }

    public function renderHtml(): string {
        $html = '';
        foreach ($this->comments as $c) {
            $a = htmlspecialchars($c['author'], ENT_QUOTES, 'UTF-8');
            $b = htmlspecialchars($c['body'], ENT_QUOTES, 'UTF-8');
            $html .= "<li><b>$a</b>: $b</li>\n";
        }
        return $html;
    }
}

$box = new CommentBox();
echo $box->add('Ada', 'Nice post!'), "\n";
echo $box->add('', 'no author'), "\n";
echo $box->add('Mallory', '<script>alert(1)</script>'), "\n";
echo "--- rendered ---\n";
echo $box->renderHtml();

Output:

accepted
rejected: empty field
accepted
--- rendered ---
<li><b>Ada</b>: Nice post!</li>
<li><b>Mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</li>

The add method validates at the input dock: Ada's comment is accepted, the empty-author one is rejected, and Mallory's script comment is accepted because a comment may legitimately contain those characters -- it is not the storage's job to strip them. At render time, renderHtml escapes each field with htmlspecialchars, so Mallory's <script> becomes inert &lt;script&gt; text in the output. Validation guarded what got in; output escaping made it safe to display.

The design flaw is that the input validation is purely structural -- presence and length -- while the safety guarantee rests entirely on the output escaping, and the two are not tied together anywhere. This is actually the correct design, but it hides a fragility: the moment a second render path is added that forgets to escape -- a JSON API returning comments, an email digest, an admin panel that builds HTML by concatenation -- the stored script payload is live again, because it was deliberately stored raw. The comment box is only as safe as its most careless output site, and nothing in the class enforces that every consumer escapes. A stricter design might return comments only through a value object whose accessors escape by default, or at least document loudly that stored bodies are untrusted and every output path must escape for its context. The subtle trap is that "store raw, escape at output" is exactly right, yet it pushes the safety obligation onto every future reader of the data -- so the flaw is not in what this code does, but in how easily a later, well-meaning addition elsewhere can reintroduce the very XSS this lesson is about, precisely because the raw payload is sitting in storage waiting for an unescaped output. The defence is discipline plus depth: make escaping the automatic default at every output boundary, review any hand-built output for missing escaping, and add a Content-Security-Policy so that even a slipped-through payload cannot easily execute.


Common Mistakes

  1. Escaping at input instead of output. Storing an HTML-escaped value corrupts it for URLs, SQL, and JSON. Store raw; escape at each point of output.
  1. Using one escaping for every context. htmlspecialchars does not make a value safe in a URL or a script block. Match the escaping to the destination.
  1. Sanitising instead of validating input. Stripping characters to "clean" input mangles legitimate data and guarantees nothing. Validate and reject; escape at output.
  1. Trusting client-side validation. Browser checks are bypassable. Re-validate every input on the server.
  1. Building SQL by escaping strings. Manual quote-escaping for SQL is error-prone. Use prepared statements with bound parameters instead.
  1. Forgetting the attribute context. An unquoted HTML attribute lets a value break out even after htmlspecialchars without ENT_QUOTES. Quote attributes and use ENT_QUOTES.
  1. Double-escaping. Escaping a value that is already escaped produces garbled &amp;lt;. Escape exactly once, at output.
  1. Assuming stored data is safe to echo. Data from the database is still untrusted for HTML. Escape it at render just like fresh input.
  1. Ignoring character encoding. Escaping without specifying UTF-8 can be bypassed with crafted encodings. Always pass the encoding to htmlspecialchars.

Best Practices

  • Validate input at the boundary and reject what fails, rather than trying to sanitise it into shape.
  • Store values raw, and escape them at each point of output for that specific context.
  • Use htmlspecialchars with ENT_QUOTES and an explicit UTF-8 encoding for HTML body and attribute output.
  • Use rawurlencode for URL components and json_encode with safe flags for values in script or JSON contexts.
  • Never build SQL by string escaping; bind values with prepared statements.
  • Re-validate every input on the server, treating any client-side checks as convenience only.
  • Quote all HTML attributes so a value cannot break out of an unquoted attribute.
  • Treat data from your own database as untrusted for output, escaping it at render exactly like fresh input.

Practice Exercises

  1. Use filter_var with FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_INT to classify a list of inputs as valid or invalid, printing the result for each.
  1. Take one string containing quotes and angle brackets and escape it three ways -- for HTML with htmlspecialchars, for a URL with rawurlencode, and for JS with json_encode -- showing the different outputs.
  1. Demonstrate why input-time escaping is wrong by storing an HTML-escaped value and showing it is broken when placed into a URL.
  1. Build a comment box that validates presence and length on input, stores raw, and escapes on HTML output, and show that a stored <script> payload renders as inert text.