PHP Functions Reference

PHP htmlspecialchars() Function: Safe HTML Output

Learn how htmlspecialchars() converts special HTML characters so untrusted text can be displayed safely in an HTML page.

PHP htmlspecialchars() Function

htmlspecialchars() converts special characters to HTML entities. It is commonly used when displaying untrusted text inside HTML text or quoted attribute values.

Basic Example

$name = '<script>alert("Hello")</script>';

echo htmlspecialchars(
    $name,
    ENT_QUOTES | ENT_SUBSTITUTE,
    "UTF-8"
);

The browser displays the text rather than interpreting it as an HTML script element.

Parameters

The function accepts the input string, an optional flags value, an optional character encoding, and an optional double_encode setting. Explicitly specifying UTF-8 makes the expected encoding clear.

ENT_QUOTES converts both single and double quotes. ENT_SUBSTITUTE replaces invalid code unit sequences instead of returning an empty string.

When to Use It

Use htmlspecialchars() when outputting plain text into HTML. It is not a universal encoder for JavaScript, CSS, URLs, or every HTML context. Each output context needs the appropriate encoding.

Practical Tip

Create a small escaping helper for templates so the same safe defaults are used consistently:

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}

Summary

htmlspecialchars() is an important defense against HTML injection when used in the correct output context. Escape untrusted values at the point where they are rendered.

Share this page Help other developers discover this resource.