htmlspecialchars() Function Use in PHP 8.5

The htmlspecialchars() function is fully supported in PHP 8.5 without any breaking changes . Its primary purpose is to convert special HTML characters into their corresponding HTML entities, which prevents user-supplied text from being interpreted as actual HTML markup or scripts (a key defense against XSS attacks).

Function Signature

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

What It Converts?

The function converts five specific characters :

1. & (Ampersand) becomes &
2. < (Less than) becomes &lt;
3. > (Greater than) becomes &gt;
4. " (Double quote) becomes &quot;
5. (Single quote) becomes &#039; (or &apos; depending on flags)

Example

<?php
$user_input = <script>alert("XSS")</script> & Tom is Book ;

// Default flags (safe for most contexts)
echo htmlspecialchars($user_input);
// Output: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt; &amp; Tom&#039;s Book

// Explicitly setting flags and encoding (recommended for consistency)
echo htmlspecialchars($user_input, ENT_QUOTES | ENT_HTML5, UTF-8 );
// Output: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt; &amp; Tom&apos;s Book
?>

Key Points for PHP 8.5

→Default Flags: Since PHP 8.1, the default flags are ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. This means both single and double quotes are escaped by default, and invalid UTF-8 sequences are replaced instead of causing an empty string.
→Use Case: Always use htmlspecialchars() when echoing user input into HTML text or attribute values. Do not use it for SQL escaping (use prepared statements) or URL encoding (use urlencode()).

6 Views