How to Use htmlspecialchars in PHP: Simple Guide
Use
htmlspecialchars in PHP to convert special characters to HTML entities, preventing them from being interpreted as HTML code. This helps protect your web pages from security issues like cross-site scripting (XSS). Simply pass the string you want to escape as the first argument to htmlspecialchars.Syntax
The htmlspecialchars function converts special characters to HTML entities to prevent them from being treated as HTML code. It takes these main parameters:
string $string: The text to convert.int $flags(optional): Controls how quotes and other characters are handled.string $encoding(optional): Character encoding, usuallyUTF-8.bool $double_encode(optional): Whether to convert existing HTML entities again.
php
string htmlspecialchars ( string $string , int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 , string $encoding = 'UTF-8' , bool $double_encode = true )
Example
This example shows how htmlspecialchars converts special characters like <, >, and quotes into safe HTML entities so they display correctly on a web page.
php
<?php $input = '<a href="test">Test & Check</a>'; $safe = htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); echo $safe; ?>
Output
<a href="test">Test & Check</a>
Common Pitfalls
Common mistakes when using htmlspecialchars include:
- Not specifying
ENT_QUOTESflag, so single quotes are not converted. - Forgetting to set the correct character encoding, which can cause issues with special characters.
- Double encoding already escaped entities, which can break HTML display.
Always use ENT_QUOTES and specify UTF-8 encoding to avoid these problems.
php
<?php // Wrong: missing ENT_QUOTES, single quotes not escaped $input = "O'Reilly & Co."; echo htmlspecialchars($input); // Right: use ENT_QUOTES to escape single and double quotes echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); ?>
Output
O'Reilly & Co.O'Reilly & Co.
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| string | The input string to convert | Required |
| flags | Controls which characters are converted (e.g., ENT_QUOTES) | ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 |
| encoding | Character encoding of the string | UTF-8 |
| double_encode | Whether to convert existing HTML entities again | true |
Key Takeaways
Use htmlspecialchars to safely display user input in HTML and prevent XSS attacks.
Always include ENT_QUOTES flag to convert both single and double quotes.
Specify UTF-8 encoding to handle special characters correctly.
Avoid double encoding by setting the double_encode parameter when needed.
htmlspecialchars only escapes special HTML characters, not full HTML sanitization.