PHP 8 Intermediate HTTP & Files · 9 min read

$_POST, Output Escaping, and XSS Prevention

Lesson 14 of 43 in the PHP 8 learning path.

How do I read a POST form and escape it before HTML?

$_POST holds the body of an application/x-www-form-urlencoded or multipart form. It is input from the browser, which means it is untrusted even when your own page rendered the form. The enrollment sample reads student_name and track, trims them, and rejects an empty value. When the values are acceptable, it prints a confirmation. Every insertion into HTML goes through htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"), including the text and the data-track attribute. ENT_QUOTES encodes both quote characters so a track named Web "Foundations" cannot break out of the attribute.

$_GET is the query string and belongs to a different lesson. $_SESSION is server-side state for a login flag. $_FILES describes an upload. This file uses $_POST only. It does not build a SQL statement. Cross-site scripting (XSS) is what happens when the raw name is echoed into HTML. SQL injection is a separate bug that a prepared statement handles later.

Syntax & Parameters

Syntax
htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')

Example

public/enroll.php
<?php

declare(strict_types=1);

function escapeHtml(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

if (PHP_SAPI === 'cli') {
    $_SERVER['REQUEST_METHOD'] = 'POST';
    $_POST['student_name'] = 'Amina <Cruz>';
    $_POST['track'] = 'Web "Foundations"';
}

$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$isPost = $method === 'POST';
$name = $isPost ? trim((string) ($_POST['student_name'] ?? '')) : '';
$track = $isPost ? trim((string) ($_POST['track'] ?? '')) : '';
$errors = [];

if ($isPost && $name === '') {
    $errors[] = 'Student name is required.';
}
if ($isPost && $track === '') {
    $errors[] = 'Track is required.';
}

echo "<!DOCTYPE html>\n<html lang=\"en\">\n";
echo "<head><meta charset=\"UTF-8\"><title>Enrollment</title></head>\n<body>\n";
echo "<h1>Enrollment</h1>\n";

if ($isPost && $errors === []) {
    echo '<p data-track="' . escapeHtml($track) . '">Received '
        . escapeHtml($name) . ' for ' . escapeHtml($track) . ".</p>\n";
} else {
    foreach ($errors as $error) {
        echo '<p>' . escapeHtml($error) . "</p>\n";
    }
    echo "<form method=\"post\" action=\"/enroll.php\">\n";
    echo '<label>Name <input name="student_name" value="' . escapeHtml($name) . "\"></label>\n";
    echo '<label>Track <input name="track" value="' . escapeHtml($track) . "\"></label>\n";
    echo "<button type=\"submit\">Enroll</button>\n</form>\n";
}

echo "</body>\n</html>\n";

Expected Output

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Enrollment</title></head>
<body>
<h1>Enrollment</h1>
<p data-track="Web &quot;Foundations&quot;">Received Amina &lt;Cruz&gt; for Web &quot;Foundations&quot;.</p>
</body>
</html>

Line-by-Line Walkthrough

  1. declare(strict_types=1) checks escapeHtml() calls in this file. It does not make $_POST values strings of a known shape. The casts below do that.
  2. escapeHtml() calls htmlspecialchars with ENT_QUOTES, ENT_SUBSTITUTE, and UTF-8.
  3. A CLI run fills $_POST with a classroom name that contains an angle bracket and a track that contains quotes, so the escape is visible without a browser.
  4. A web request leaves those superglobals alone and reads the real POST body. $_GET, $_SESSION, and $_FILES are other inputs and are not read here.
  5. The script trims student_name and track and treats a missing key as an empty string.
  6. Empty required fields become error messages. The sample errors are fixed strings and are still escaped.
  7. On a valid POST the confirmation paragraph puts the track in a quoted attribute and in the text, both through escapeHtml().
  8. Amina <Cruz> becomes Amina &lt;Cruz&gt; in the text, which is how the page prevents cross-site scripting (XSS).
  9. Web "Foundations" becomes Web &quot;Foundations&quot; in the attribute because ENT_QUOTES encodes double quotes.
  10. The GET path prints the form with empty escaped values. This run is a POST, so the confirmation is what the script prints. No SQL is built.

Common Pitfalls & Security

Cross-site scripting (XSS) is the bug this page closes: the browser treats < as markup unless the server encodes it. SQL injection (SQLi) is a different bug. Encoding for HTML does not make a string safe to concatenate into a query, and a prepared statement does not make a string safe to drop into HTML. Do both at the right boundary. Never trust the client, including hidden fields and the values your own form just rendered.

  • Unsafe anti-pattern (do not ship): echo $_POST["student_name"]; writes the raw field into HTML and is an XSS bug.
  • htmlspecialchars without ENT_QUOTES leaves single quotes intact. An attribute wrapped in single quotes can still be broken.
  • Trim and empty checks are validation. They are not encoding. A non-empty name can still contain < and ".
  • $_GET is for links and query strings, $_SESSION for server-side login state, and $_FILES for uploads. Reading the wrong array silently accepts empty input.
  • Building INSERT with the posted name is SQLi. This file stops at HTML. The INSERT article binds the value instead.
  • Trusting a hidden input such as role=admin is the same mistake as trusting the visible name. Authorize on the server.

Best Practices & Modern Standards

On PHP 8.3, cast request fields to string, trim them, validate the ones you will keep, and encode them at the HTML boundary with htmlspecialchars and the flags in escapeHtml(). Keep declare(strict_types=1) on the front controller so helpers that expect strings are not handed arrays by accident. A form library or a Laravel form request can wrap the same rules. The encoding step remains mandatory.

Store the original text. Encode on output, not on the way into the database, or the next page will double-encode it. When the same confirmation is also returned as JSON, skip HTML encoding and set the JSON content type instead. Encoding is a property of the format you are producing.

Real-World Use

The enrollment form posts student_name and track to public/enroll.php. A student types Amina <Cruz> and the track Web "Foundations". The confirmation shows the brackets and quotes as text because both spots are escaped. The registrar sees the intended name, the browser does not run a tag, and the script still has not written SQL. Saving the row is the prepared INSERT that follows a valid form.

Frequently Asked Questions

Does htmlspecialchars stop SQL injection?

No. It encodes HTML. SQL injection is stopped by keeping the value out of the SQL text and binding it in a prepared statement. This enrollment page does not run a query.

Why encode the attribute and the text?

They are different HTML contexts that both break on quotes or angle brackets. ENT_QUOTES covers the attribute quotes, and the same call covers < in the paragraph text.

Where do $_GET, $_SESSION, and $_FILES fit?

$_GET reads the query string. $_SESSION reads server-side data tied to the session cookie, such as a login flag. $_FILES describes an upload. This sample reads $_POST because the enrollment form uses method post.

Should I escape before saving the name?

Save the characters the student typed. Escape when you print HTML. Escaping before storage turns a later JSON response or a second escape into visible &amp; entities.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…