Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

htmlspecialchars

Replaces HTML special characters with safe entities.

Syntax

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

Parameters

ParameterTypeDescription
$stringstringThe source string.
$flagsintOptional. Which quotes to convert; both single and double by default.
$encoding?stringOptional. The encoding; UTF-8 by default.

Return value

stringA string safe to print into HTML.

Examples

Tags become plain text:

<?php
 
echo htmlspecialchars('<script>alert(1)</script>');

Output:

&lt;script&gt;alert(1)&lt;/script&gt;

Quotes in an attribute value:

<?php
 
$name = 'Tom "The Cat"';
 
echo '<input value="' . htmlspecialchars($name) . '">';

Output:

<input value="Tom &quot;The Cat&quot;">

Notes

This is the main defence against XSS: escape everything that came from a user and is printed on a page. Escape on output, not when saving to the database.

See also

  • strip_tags — Removes HTML tags from a string.
  • nl2br — Inserts a br tag before every line break.

Related recipes

In the tutorial

  • Security — The basics of PHP site security — XSS and escaping, SQL injection, password hashing, CSRF tokens and validating input.

Thanks for reading!

Donate to the site — we work hard for you.