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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
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 &amp; alone. Default: true

Return value

The escaped string.

Examples

Make user input safeTry it yourself
<?php
$name = '<script>alert("hi")</script>';
echo htmlspecialchars($name), "\n";

Output

&lt;script&gt;alert(&quot;hi&quot;)&lt;/script&gt;
Inside an HTML attributeTry it yourself
<?php
$title = "Tom's \"best\" cafe";
echo '<input value="' . htmlspecialchars($title) . '">', "\n";

Output

<input value="Tom&#039;s &quot;best&quot; 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: use json_encode() or urlencode() there.

Version history

VersionChange
PHP 4.0Added
PHP 8.1The default flags became ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, so single quotes are escaped by default.

Was this page helpful?