Skip to main content

Lesson 2 of 7

XSS - Cross-Site Scripting Prevention

XSS attacks inject malicious scripts into web pages served to other users. Types: Stored XSS (injected data persisted in DB then displayed), Reflected XSS (injected data echoed from the request), DOM-based XSS (client-side manipulation). Prevention: encode output at every output point - not just at input time.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

XSS Prevention - Output Encoding & CSP

XSS Prevention - Output Encoding & CSP
<?php
declare(strict_types=1);

// ── How XSS works ─────────────────────────────────────────────
// User submits: <script>document.cookie</script>
// Stored in DB.
// Another user views the page - the script executes in THEIR browser.
// The attacker receives their session cookie → account hijacking.

// ── htmlspecialchars - the primary defense ────────────────────
// Converts: <  >  "  '  &  into HTML entities
// &lt; &gt; &quot; &#039; &amp;

// ❌ Vulnerable - raw echo
echo $post["title"];   // <script>alert(1)</script> executes!

// ✅ Safe - entity-encoded
echo htmlspecialchars($post["title"], ENT_QUOTES, "UTF-8");
// Output: &lt;script&gt;alert(1)&lt;/script&gt; - displays as text, not code

// ── Helper function - use everywhere ─────────────────────────
function e(mixed $value): string {
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}

// In templates:
echo '<h1>' . e($post["title"]) . '</h1>';
echo '<p class="author">By ' . e($user["name"]) . '</p>';
echo '<input value="' . e($old["title"] ?? "") . '">';

// ── Context matters - different encoding for different contexts ──
// HTML body:    htmlspecialchars()
// HTML attribute: htmlspecialchars() - always use quotes around attributes!
// URL:          urlencode() for values in query strings
// JavaScript:   json_encode() - never embed PHP directly in JS

// ❌ Dangerous - embedding PHP in JavaScript:
echo "<script>var user = '{$user['name']}';</script>";
// If name = '; alert(document.cookie); var x = ' → XSS!

// ✅ Safe - use json_encode:
$safeUserData = json_encode(["name" => $user["name"]], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
echo "<script>var user = {$safeUserData};</script>";

// ── Content Security Policy (CSP) header - defense in depth ──
// Tells browsers where scripts can come from - even if XSS succeeds,
// inline scripts and foreign CDNs are blocked
header("Content-Security-Policy: " . implode("; ", [
    "default-src 'self'",
    "script-src 'self'",            // no inline scripts, no foreign JS
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' data: https:",
    "font-src 'self'",
    "frame-ancestors 'none'",       // no clickjacking
    "base-uri 'self'",
]));

// ── Other security headers ────────────────────────────────────
header("X-Content-Type-Options: nosniff");  // no MIME sniffing
header("X-Frame-Options: DENY");             // no iframing
header("Referrer-Policy: strict-origin-when-cross-origin");
header("Permissions-Policy: geolocation=(), camera=(), microphone=()");

Quick Quiz

Tip

Tip

Practice XSS CrossSite Scripting Prevention in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for XSS - Cross-Site Scripting Prevention

Practice Task

Note

Practice Task - (1) Write a working example of XSS CrossSite Scripting Prevention 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 XSS CrossSite Scripting Prevention is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done