htmlspecialchars
Replaces HTML special characters with safe entities.
Syntax
htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source string. |
| $flags | int | Optional. Which quotes to convert; both single and double by default. |
| $encoding | ?string | Optional. 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:
<script>alert(1)</script>Quotes in an attribute value:
<?php
$name = 'Tom "The Cat"';
echo '<input value="' . htmlspecialchars($name) . '">';Output:
<input value="Tom "The Cat"">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.