Escape output to prevent XSS in PHP
A short helper around htmlspecialchars with the right flags for HTML text and attribute values.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?php
function e(?string $value): string
{
return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}Example / expected output
<p>Hello <?= e($_GET['name'] ?? 'guest') ?></p>How it works
Escape on output, in the context where the value is used. ENT_QUOTES also escapes single quotes so values are safe inside attributes, and ENT_SUBSTITUTE replaces invalid UTF-8 instead of returning an empty string. Do not use this for URLs (validate the scheme) or for JavaScript contexts (use json_encode).
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.

