PHP - htmlspecialchars
Trieda
Metóda - htmlspecialchars
(PHP 4, PHP 5, PHP 7)
The key function which converts special characters into HTML entities.
Special characters include: &, ',
", <, >. This
function is very important and it should be used when printing most of the
variables to avoid disruption of the HTML document by user's characters or
eventually to avoid XSS attack.
The function does not convert all characters for which there are entities,
but only the basic ones. If you need to convert all characters (what is not
usually the case because e.g. diacritics would be broken), use the
htmlentities() function.
Procedurálne
- function htmlspecialchars (string $string, int $flags = ENT_COMPAT | ENT_HTML401, string $encoding = ini_get("default_charset"), bool $double_encode = true) : string
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| $string | string | The string being converted. | |||||||||||||||||||||
| $flags | int | ENT_COMPAT | ENT_HTML401 | We can set so-called flags as the second parameter. These constants change
the behavior of the function. These constants can be joined by
| ||||||||||||||||||||
| $encoding | string | ini_get("default_charset") | The optional parameter is encoding (most often as | ||||||||||||||||||||
| $double_encode | bool | true | If the parameter is set to FALSE, the existing HTML entities will be not converted. Otherwise, each entity will be converted. |
Mávratovej hodnoty
Vracia: string
The converted string.
Príklady
<?php
$s = 'Welcome to the forum! Your problem will be solved by a </body> tag because you do not have a closed body tag.';
echo htmlspecialchars($s);
Without using the htmlspecialchars() function, the
</body> tag would be added into the page, so the page would
be broken.
Let's show what happens if we change the value of the last parameter:
<?php
echo htmlspecialchars('The entity < is used for less-than sign');
echo ('<br />');
echo htmlspecialchars('The entity < is used for less-than sign', ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
As we can see, in the first case, the entity was converted, but in the second one the function did not change the entity.
Súvisiace manuály
- function htmlspecialchars_decode (string $string, int $flags = ENT_COMPAT | ENT_HTML401) : string
- function nl2br (string $string, bool $is_xhtml = true) : string
- function strip_tags (string $str, string $allowable_tags) : string
