How to Escape HTML in PHP
Escaping HTML in PHP is important to prevent Cross-Site Scripting (XSS) attacks. When you output user-generated content (such as form inputs, comments, or database values) directly into HTML, it may contain special characters like < or > that the browser could interpret as HTML or JavaScript.
To safely display such content, you should escape it using PHP’s htmlspecialchars() function.
PHP Helper Function
function esc(?string $str): string {
return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
}
Example Usage
<?= esc($user->name) ?>
This ensures any HTML characters in the value are safely converted before being rendered in the browser.
Why Escaping HTML is Important
Without escaping, malicious input like this:
<script>alert('XSS')</script>
could execute JavaScript in the user’s browser.
When escaped, it becomes harmless text:
<script>alert('XSS')&lt;/script&gt;