Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Using PHP htmlspecialchars() to Escape Special Characters

Using PHP htmlspecialchars() to Escape Special Characters

This article explains the PHP htmlspecialchars() function, its syntax and parameters, demonstrates how to escape special characters, quotes, and specify encoding or disable double‑encoding, and shows how it helps prevent XSS attacks in web applications.

When developing web applications, safely handling user input is essential, and the PHP htmlspecialchars() function is commonly used to escape special characters in strings.

htmlspecialchars() Function Syntax

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" [, bool $double_encode = true ]]] )
$string

: Required. The string to be escaped. $flags: Optional. Determines how quotes are handled; default is ENT_COMPAT | ENT_HTML401. $encoding: Optional. Character encoding, default is "UTF-8". $double_encode: Optional. Whether to escape already escaped characters; default is true.

The function converts special characters such as &, ", ', <, and > into their corresponding HTML entities, preventing cross‑site scripting (XSS) attacks.

Example: Escaping Special Characters

$input = '<script>alert("Hello!");</script>';
$output = htmlspecialchars($input);
echo $output; // Output: &lt;script&gt;alert(&quot;Hello!&quot;);&lt;/script&gt;

This example shows how htmlspecialchars() transforms a script tag into safe HTML entities.

Example: Escaping Quotes with ENT_QUOTES

$input = 'I\'m "John"';
$output = htmlspecialchars($input, ENT_QUOTES);
echo $output; // Output: I&#039;m &quot;John&quot;

Using the ENT_QUOTES flag also escapes both single and double quotes.

Example: Specifying Character Encoding

$input = '中文字符';
$output = htmlspecialchars($input, ENT_QUOTES, 'GBK');
echo $output; // Output: 中文字符

When the specified encoding matches the output environment, no conversion occurs.

Example: Disabling Double Encoding

$input = 'special & character';
$output = htmlspecialchars($input, ENT_QUOTES, 'UTF-8', false);
echo $output; // Output: special &amp; character

Setting $double_encode to false prevents already‑escaped characters from being encoded again.

The htmlspecialchars() function is a widely used PHP tool that helps developers securely process user input, mitigate XSS risks, and ensure the reliability of web applications.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
backendPHPXSShtmlspecialcharsstring escaping

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion