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 <
3. > (Greater than) becomes >
4. " (Double quote) becomes "
5. (Single quote) becomes ' (or ' 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: <script>alert("XSS")</script> & Tom's Book// Explicitly setting flags and encoding (recommended for consistency)
echo htmlspecialchars($user_input, ENT_QUOTES | ENT_HTML5, UTF-8 );
// Output: <script>alert("XSS")</script> & Tom'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()).