This post covers the Cross-Site Scripting section of the PHP Security chapter when studying for the Zend PHP 7 Certification.
Cross Site Scripting (XSS) is one of the most common form of security attacks that happen on the Internet.
The attack focuses on injecting code which is made possible by incorrectly validating user data, which usually gets inserted into the page through a web form or using an altered hyperlink.
Luckily as easy as it may be that systems are vulnerable to this attack, it is just as easy to prevent XSS attacks by using some of PHP’s in built functions.
In any programming language, it is very important to properly escape output, and
htmlspecialchars() in PHP converts special characters to HTML entities.
The below shows the list of characters that get converted.
Here is an example of
htmlspecialchars() in action.
htmlspecialchars() will only convert the special characters listed above and not anything else.
For other entities, you should use the
htmlentities() function. This function is identical to
htmlspecialchars() except all characters which have HTML character entity equivalents are translated into these entities.
The default configuration of
htmlentities may not protect against XSS attacks, therefore you can also specify a
$flag as a second parameter. For example,
ENT_QUOTES ensures that both single and double quotes get converted.
strip_tags() strips HTML and PHP tags from a string.
strip_tags() function also gives you the ability to keep tags within the string from being removed.
By passing in a second parameter, you can add tags that you would like to preserve in the string, like so:
strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.
View the other sections:
Note: This article is based on PHP version 7.0.