Escape HTML entities to prevent Cross-Site Scripting attacks.
Code
General// Escape HTML entities to prevent XSS
$safeOutput = htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $safeOutput;Parameters
Untrusted user input (try a malicious payload)
What is XSS?
Cross-Site Scripting (XSS) occurs when untrusted data is included in a web page without proper escaping. An attacker can inject malicious scripts that execute in other users' browsers.
// DANGEROUS: Directly echoing user input
"<div>Welcome, $userInput!</div>";
// If $userInput is "<script>alert('XSS')</script>", the script executes!
Why htmlspecialchars() Works
The function converts dangerous characters to HTML entities:
| Character | Escaped | Why |
|---|---|---|
< | < | Prevents opening tags |
> | > | Prevents closing tags |
" | " | Prevents breaking out of attributes |
' | ' | Prevents breaking out of attributes (with ENT_QUOTES) |
& | & | Prevents entity injection |
The Flags Matter
// GOOD: Escape both single and double quotes, use HTML5 entities
htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// BAD: Default only escapes double quotes
htmlspecialchars($input); // Single quotes can still break attributes!
Create a Helper Function
function e($str) {
return htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Usage
"<div>Welcome, " . e($userInput) . "!</div>";
The Rule
Always use htmlspecialchars() with ENT_QUOTES when outputting untrusted data in HTML.
More PHP Snippets
Hash SHA-256
Generate a SHA-256 hash of a string.
SQL Injection Prevention
Use parameterized queries to prevent SQL injection attacks.
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.