PHP 8 reference · String Functions
PHP htmlspecialchars() Function
Convert &, <, >, " and ' to HTML entities so user text is shown as text, not run as HTML. The main defence against XSS.
PHP 8 Since 4.0
Syntax
htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string
Parameters
| Parameter | Description |
|---|---|
string |
The input string. |
flags optional |
How to treat quotes and invalid code units. Default: ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 |
encoding optional |
The character encoding; defaults to UTF-8. |
double_encode optional |
false leaves existing entities such as & alone. Default: true |
Return value
The escaped string.
Examples
<?php
$name = '<script>alert("hi")</script>';
echo htmlspecialchars($name), "\n";
Output
<script>alert("hi")</script>
<?php
$title = "Tom's \"best\" cafe";
echo '<input value="' . htmlspecialchars($title) . '">', "\n";
Output
<input value="Tom's "best" cafe">
Common mistakes
- Escape when you output to HTML, not when you save to the database.
- It doesn't make text safe inside
<script>blocks or URLs: usejson_encode()orurlencode()there.
Version history
Related
html_entity_decode()· Convert HTML entities such as &, < and é back into the characters they stand for.strip_tags()· Remove HTML and PHP tags from a string, keeping the text. You can allow some tags, but it's no XSS protection.nl2br()· Insert an HTML <br> tag before every new line in a string, so plain text keeps its line breaks on a web page.- PHP Form Handling · tutorial
- PHP Strings · tutorial