1.2.527. Htmlentities Calls

htmlentities() and htmlspecialchars() are used to prevent injecting special characters in HTML code. As a bare minimum, they take a string and encode it for HTML.

The second argument of the functions is the type of protection. The protection may apply to quotes or not, to HTML 4 or 5, etc. It is highly recommended to set it explicitly.

The third argument of the functions is the encoding of the string. In PHP 5.3, it is ISO-8859-1, in 5.4, was UTF-8, and in 5.6, it is now default_charset, a php.ini configuration that has the default value of UTF-8. It is highly recommended to set this argument too, to avoid distortions from the configuration. Also, note that arguments 2 and 3 are constants and string, respectively, and should be issued from the list of values available in the manual. Other values than those will make PHP use the default values.

<?php
$str = 'A quote is <b>bold</b>';

// Outputs, without depending on the php.ini: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES, 'UTF-8');

// Outputs, while depending on the php.ini: A quote is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

?>

See also htmlentities and htmlspecialchars.

1.2.527.1. Suggestions

  • Always use the third argument with htmlentities()

1.2.527.2. Specs

Short name

Structures/Htmlentitiescall

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Instant (5 mins)

Precision

Very high

Features

html-entity

Related rule

Htmlentities Using Default Flag

Available in

Entreprise Edition, Community Edition, Exakat Cloud