Open In App

What is htmlspecialchars() Function in PHP?

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The htmlspecialchars() function in PHP is used to convert special characters to HTML entities. This is particularly useful for preventing XSS (Cross-site Scripting) attacks by ensuring that any special characters in user input are not interpreted as HTML by the browser.

For example, characters like <, >, &, and " have special meanings in HTML, and they can be used to inject malicious code into a web page. By converting these characters to their corresponding HTML entities, you can safely display the data without the risk of executing unintended code.

Syntax:

htmlspecialchars(string,flags,character-set,double_encode)

Where:

  • string: The string to be converted.
  • flags (optional): A bitmask of one or more of the following flags, combined by bitwise OR (|). The default is ENT_COMPAT.
    • ENT_COMPAT: Will convert double quotes and leave single quotes alone.
    • ENT_QUOTES: Will convert both double and single quotes.
    • ENT_NOQUOTES: Will leave both double and single quotes unconverted.
    • ENT_HTML401, ENT_HTML5, ENT_XML1, ENT_XHTML: Handle the quote style for specific document types.
  • Character-set(optional): the character encoding of the string to be converted. for example: 'UTF-8', 'ISO-8859-1', 'ISO-8859-15', 'cp1252', etc.
  • double_encode (optional): It accepts Boolean value(True, False), This parameter specifies whether to convert existing HTML entities in input string or not. By default it is set to True.

Return Value:

Returns the converted string.

Example 1: This example shows the use of htmlspecialchars() function that will convert the given string into the HTML entities.

PHP
<?php
$string = "<h1>Hello, World!</h1>";
$converted_string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
echo $converted_string;
?>

Output
&lt;h1&gt;Hello, World!&lt;/h1&gt;

Example 2: This example shows how the function is handling the quotes present in the given string.

PHP
<?php
$string = 'She said "Hello" and left.';
$converted_string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
echo $converted_string;
?>

Output
She said &quot;Hello&quot; and left.

Example 3: In this example, the ENT_HTML5 flag is used to ensure the conversion is suitable for HTML5 documents, which allows for the conversion of single quotes to &apos;.

PHP
<?php
$string = "A 'quote' is <b>bold</b>";
$converted_string = htmlspecialchars($string,
                    ENT_QUOTES | ENT_HTML5, 'UTF-8');
echo $converted_string;

?>

Output
A &apos;quote&apos; is &lt;b&gt;bold&lt;/b&gt;

Next Article
Article Tags :

Similar Reads