PHP htmlspecialchars() Function
PHP htmlspecialchars() Syntax
htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string
PHP htmlspecialchars() Basic examples
echo htmlspecialchars("<b>Hello</b>");
<b>Hello</b>
Escapes HTML tags.
PHP htmlspecialchars() Real-world usage
$input = "<script>alert(1)</script>";
echo htmlspecialchars($input, ENT_QUOTES);
<script>alert(1)</script>
Prevents XSS attacks when displaying user input.
PHP htmlspecialchars() Edge cases
echo htmlspecialchars("\"quoted\"");
"quoted"
Quotes are escaped when ENT_QUOTES is used.
PHP htmlspecialchars() Common mistakes
Double-escaping content
Applying htmlspecialchars multiple times leads to broken output.
echo htmlspecialchars(htmlspecialchars("<b>Hi</b>"));
echo htmlspecialchars("<b>Hi</b>");
Escape content exactly once at output time.
PHP htmlspecialchars() Frequently Asked Questions
What does htmlspecialchars() do in PHP?
htmlspecialchars() converts special characters to HTML entities to prevent HTML rendering.
Which characters are converted by htmlspecialchars()?
It converts &, <, >, " and optionally single quotes depending on flags.
Is htmlspecialchars() safe for user input?
Yes, it is commonly used to prevent XSS by escaping user input.
What is the difference between htmlspecialchars() and htmlentities()?
htmlspecialchars() converts only a few characters, while htmlentities() converts all applicable characters.
Does htmlspecialchars() modify the original string?
No, it returns a new escaped string.
What encoding should be used with htmlspecialchars()?
UTF-8 is recommended for modern applications.
What flags can be used with htmlspecialchars()?
Common flags include ENT_QUOTES, ENT_NOQUOTES, and ENT_SUBSTITUTE.
Can htmlspecialchars() prevent all XSS attacks?
It helps prevent XSS but must be used correctly depending on context.
Does htmlspecialchars() handle quotes?
Yes, depending on flags, it can escape both single and double quotes.
Is htmlspecialchars() reversible?
Yes, you can use htmlspecialchars_decode() to reverse it.
What is a real-world use case of htmlspecialchars()?
Displaying user input safely in HTML pages.
Should htmlspecialchars() be used in templates?
Yes, it is best practice to escape output in templates.