PHP htmlspecialchars() Function

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The htmlspecialchars() function is PHP’s primary tool for output escaping. It converts &, <, >, and quotes into HTML entities so user input displays as text instead of running as code.

01

Escape Output

&, <, >, quotes.

02

Prevent XSS

Block script tags.

03

ENT_QUOTES

Encode ' and ".

04

UTF-8

Always specify it.

05

vs htmlentities

Subset vs full.

06

On Output

Escape when echoing.

Definition and Usage

In PHP, htmlspecialchars() prepares dynamic text for safe inclusion in HTML documents. Characters with special meaning in HTML are replaced with entities so browsers render them literally. This is essential whenever you echo user input, database values, or any untrusted string into a web page.

🛡
Security Rule

Escape at output, not only at input. The standard pattern is htmlspecialchars($value, ENT_QUOTES, 'UTF-8') right before echoing into HTML. Pair with prepared statements for SQL—never use htmlspecialchars for database queries.

📝 Syntax

The function accepts a string, flags, encoding, and double-encode option:

PHP
string htmlspecialchars(
    string $string,
    int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,
    ?string $encoding = null,
    bool $double_encode = true
)

Characters Encoded

  • &&amp;
  • <&lt;
  • >&gt;
  • "&quot; (unless ENT_NOQUOTES)
  • '&#039; or similar (when ENT_QUOTES is set)

Parameters

  • $string — input text to escape.
  • $flags — quote and document-type bitmask. Use ENT_QUOTES for web output.
  • $encoding — character encoding (strongly recommended: 'UTF-8').
  • $double_encode — when true (default), encodes existing entities again; when false, leaves existing entities unchanged.

Return Value

Returns the escaped string safe for HTML text and attribute contexts (when using ENT_QUOTES).

⚡ Quick Reference

Standard escape
htmlspecialchars($s, ENT_QUOTES, 'UTF-8')

Use this pattern

Echo safely
echo htmlspecialchars($user, ENT_QUOTES, 'UTF-8');

Output escaping

Decode pair
htmlspecialchars_decode($s, ENT_QUOTES)

Reverse escaping

Full entities
htmlentities($s, ENT_QUOTES, 'UTF-8')

When you need more

Examples Gallery

Run these examples in PHP 7+. Each demonstrates a common pattern beginners encounter with htmlspecialchars().

📚 Getting Started

Neutralize script tags and HTML markup in user input.

Example 1 — Prevent XSS from a Script Tag

Without escaping, a <script> tag would execute in the browser. Escaping renders it as visible text.

PHP
<?php
$userInput = '<script>alert("XSS")</script>';
$safe      = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

echo "Raw:  $userInput\n";
echo "Safe: $safe\n";
?>

How It Works

Angle brackets and quotes become entities. When echoed into HTML, the browser shows the text literally instead of running JavaScript.

📈 Practical Patterns

Compare encoders, quote flags, and double-encoding behavior.

Example 3 — htmlspecialchars() vs htmlentities()

See what each function encodes for symbols and accented text.

PHP
<?php
$text = "Tom & Jerry © 2026 — €5";

$special = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
$full    = htmlentities($text, ENT_QUOTES, 'UTF-8');

echo "htmlspecialchars: $special\n";
echo "htmlentities:     $full\n";
?>

How It Works

Both encode &. Only htmlentities() converts ©, em dashes, and €. For XSS prevention, the smaller output from htmlspecialchars() is usually enough.

Example 4 — ENT_QUOTES vs ENT_COMPAT

Single quotes matter when output lands inside single-quoted HTML attributes.

PHP
<?php
$name = "O'Brien";

$compat = htmlspecialchars($name, ENT_COMPAT, 'UTF-8');
$quotes = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');

echo "ENT_COMPAT: $compat\n";
echo "ENT_QUOTES: $quotes\n";
?>

How It Works

ENT_COMPAT leaves apostrophes unencoded. ENT_QUOTES encodes them—required for safe use inside attribute='...' contexts.

Example 5 — double_encode = false

Prevent re-encoding strings that already contain HTML entities.

PHP
<?php
$partial = "Already has &copy; symbol";

$again = htmlspecialchars($partial, ENT_QUOTES, 'UTF-8', true);
$once  = htmlspecialchars($partial, ENT_QUOTES, 'UTF-8', false);

echo "double_encode true:  $again\n";
echo "double_encode false: $once\n";
?>

How It Works

Default true encodes the & in &copy; again. Setting false preserves existing entities while still encoding unescaped characters elsewhere in the string.

🚀 Common Use Cases

  • Echoing user input — comments, names, search terms displayed on a page.
  • HTML attribute values — escape with ENT_QUOTES for title, value, and data attributes.
  • Error and status messages — safely show dynamic feedback without injecting markup.
  • Admin dashboards — display stored data that may contain special characters.
  • Template rendering — escape variables before inserting into HTML layouts.

🧠 How htmlspecialchars() Works

1

You pass plain text

Dynamic or user-supplied string plus ENT flags, UTF-8 encoding, and optional double_encode.

Input
2

PHP scans for special chars

Looks for &, <, >, and quotes based on the HTML_SPECIALCHARS translation table.

Transform
3

Entities replace characters

Each special character becomes an entity string like &lt; or &quot;.

Encode
=

Safe HTML string

Ready to echo into HTML body or attributes.

📝 Notes

  • Default flags changed in PHP 8.1 to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.
  • Always pass 'UTF-8' explicitly for modern applications.
  • Escape at output time—store raw data in the database when possible.
  • Not sufficient for JavaScript or CSS contexts—those need context-specific escaping.
  • Does not encode ©, €, or accented letters—use htmlentities() if you need full entity encoding.

Conclusion

The htmlspecialchars() function is the foundation of safe HTML output in PHP. Use htmlspecialchars($text, ENT_QUOTES, 'UTF-8') whenever you echo dynamic data into a web page.

It prevents XSS by encoding dangerous characters, pairs with htmlspecialchars_decode() for reversal, and covers most escaping needs without the overhead of full htmlentities() encoding.

💡 Best Practices

✅ Do

  • Use htmlspecialchars($s, ENT_QUOTES, 'UTF-8') on every HTML output
  • Escape at output time, not only at input
  • Use prepared statements for SQL (separate concern)
  • Set double_encode to false for partially encoded input
  • Combine with Content Security Policy for defense in depth

❌ Don’t

  • Echo raw user input without escaping
  • Use htmlspecialchars for SQL injection prevention
  • Assume escaping input once at save time is enough forever
  • Skip escaping because input “looks safe”
  • Double-escape by calling htmlspecialchars twice on the same string

Key Takeaways

Knowledge Unlocked

Five things to remember about htmlspecialchars()

Use these points whenever you output dynamic text in PHP.

5
Core concepts
🛠 02

ENT_QUOTES + UTF-8

Standard pattern.

Syntax
03

Prevent XSS

Block script tags.

Security
📈 04

vs htmlentities

Subset is enough.

Compare
🔄 05

Decode Pair

htmlspecialchars_decode().

Related

❓ Frequently Asked Questions

htmlspecialchars() converts special HTML characters to entities so they display as plain text instead of being interpreted as markup. It encodes &, <, >, and quotes (depending on flags)—the standard defense against XSS when echoing data into HTML.
string htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true). The recommended pattern for web apps is htmlspecialchars($text, ENT_QUOTES, 'UTF-8').
htmlspecialchars() encodes only the core special characters (&, <, >, quotes). htmlentities() encodes every character with an HTML entity equivalent—including ©, €, and accented letters. For typical output escaping, htmlspecialchars() is enough.
ENT_QUOTES encodes both single and double quotes, preventing attribute-breakout attacks. UTF-8 ensures multibyte characters are handled correctly. Always pass both explicitly instead of relying on PHP defaults.
Call it at output time—whenever you echo user-controlled or dynamic data into HTML (body text, attributes, or JavaScript string contexts may need additional escaping). Do not use it as a substitute for prepared statements for SQL.
Use htmlspecialchars_decode() with matching ENT flags: htmlspecialchars_decode($encoded, ENT_QUOTES). Only decode when you need plain text for processing; re-escape before displaying in HTML again.

Explore More PHP String Functions

Continue with implode(), explode(), and the rest of the string function reference.

Next: implode() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful