Use htmlspecialchars() when untrusted or variable text is placed into normal HTML text or attribute contexts. Escaping is an output step: keep the original data unchanged and escape it for the context where it is rendered.
$input = '<strong>Tom & Jerry</strong>';
echo htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');The examples below show additional variations, expected output and practical usage.
Rendered as HTML, the tags in the sample affect presentation:
To show the markup itself as text, escape it before inserting it into the page:
$sample = '<b>Hello this is bold</b> <i>This is italic</i>';
echo htmlspecialchars($sample, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
The browser then displays the angle brackets instead of interpreting them as HTML.
<b>Hello this is bold</b> <i>This is italic</i>
By default, htmlspecialchars() converts characters that have special meaning in HTML, including &, <, > and quotes according to the selected flags. For modern UTF-8 pages, explicitly passing ENT_QUOTES | ENT_SUBSTITUTE and 'UTF-8' makes the intended behavior clear.
$input = "<script>alert('XSS');</script>";
$escaped_input = htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo $escaped_input; // <script>alert('XSS');</script>
$str = 'Hello & welcome!';
echo htmlspecialchars($str); // Output: Hello & welcome!
$str = '© 2023 Plus2Net';
echo htmlspecialchars($str); // Output: © 2023 Plus2Net
echo htmlentities($str); // Output: © 2023 Plus2Net
These examples show how HTML output escaping preserves text safely for display. Escaping is context-specific and should not be confused with changing or sanitizing the stored input.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| webchecker | 17-02-2010 |
| very good explanation, thank you | |