PHP htmlentities() Function

What is PHP htmlentities() Function?

HTML entities are special sequence of characters that are used in HTML to display – reserved characters (like <, >, &, “, ‘), hidden characters (like non-breaking space), and some special symbols (like © – copyright symbol).

If you want to convert some special sequence of characters to its equivalent HTML entity, use htmlentities() function. So, the function converts the reserved character < to its HTML entity “&lt;”.

Syntax:

htmlentities(string, flags, encoding, double_encode)

Parameters:

The Function has 1 required parameter and 3 optional parameters-

string (Required): It specifies a string that you want to convert to HTML entity.

flags (Optional): It specifies how to handle quotes, invalid encoding and the used document type. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

encoding (Optional): It specifies the encoding used when converting characters. If omitted, encoding defaults to the value of the default_charset configuration option. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the default_charset configuration option may be set incorrectly for the given input.

double_encode (Optional): It determines whether to encode the existing HTML entities or not. It has 2 values- It determines whether to encode the existing entity again. if the string already contains an entity. It has 2 values-

  • TRUE – It is the default value. It will encode the existing HTML entities.
  • FALSE – It won’t encode the existing HTML entities.

Return Values:

The function returns the converted (encoded) string. However, if the $string parameter contains invalid encoding, it will return an empty $string, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set

Examples:

Example 1:

&lt;?php
$string = "&lt;script>alert('Hello');&lt;/script>";
echo htmlentities($string);
?>

Output:

&lt;script&gt;alert(&#039;Hello&#039;);&lt;/script&gt;

Explanation:

In the view source of the browser, you’ll see this.

Example 2:

&lt;?php
$str = "They're learning PHP";
echo htmlentities($str, ENT_NOQUOTES);
?>

Output:

They're learning PHP

Explanation:

In the view source of the browser, you’ll see this.

Practical Usages of htmlentities() Function:

This function is useful for preventing XSS attacks by displaying user generated content as text rather than executable HTML or script.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP htmlentities() Function

htmlentities() function is one of the built-in string functions. Use this function to encode characters to its equivalent HTML entity.

Reference:

https://www.php.net/manual/en/function.htmlentities.php