PHP Code Examples

How to Safely Display User Input in HTML with PHP

Prevent HTML injection by escaping dynamic text with htmlspecialchars() and using the correct output context.

Example

<?php
$comment = $_POST['comment'] ?? '';

function escapeHtml(string $value): string
{
    return htmlspecialchars(
        $value,
        ENT_QUOTES | ENT_SUBSTITUTE,
        'UTF-8'
    );
}
?>

<p><?= escapeHtml($comment) ?></p>

Explanation

Never insert untrusted text directly into HTML. htmlspecialchars() converts characters such as <, >, &, and quotes into HTML entities.

Important

HTML escaping is context-specific. JavaScript, CSS, URLs, and HTML attributes can require different handling. Prefer avoiding inline JavaScript and build URLs with appropriate URL-encoding functions.

Share this page Help other developers discover this resource.