Skip to content
GreenSnippets

Escape output to prevent XSS in PHP

A short helper around htmlspecialchars with the right flags for HTML text and attribute values.

PHP
<?php
function e(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

Example / expected output

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).