Zend PHP 7 Certification – Security – Escape Output

This post covers the Escape Output section of the PHP Security chapter when studying for the Zend PHP 7 Certification.

One of the fundamentals rules of security in any programming language is escaping output. Consider the following script that is vulnerable to a Cross-Site Scripting (XSS) attack.

<?php
$name = $_GET['name'];  
echo "Hi $name!";

The two main issues with the above is that the input isn’t filtered and that the output isn’t escaped. This means that an attacker could attack a URL like http://example.com/yourscript.php?name= and then then send that URL to someone else which then could steal a user’s sensitive information.

PHP provides functions to escape output, including htmlspecialchars(), htmlentities() and strip_tags().

The htmlspecialchars() function converts special characters to HTML entities.

Zend PHP 7 Certification

Zend PHP 7 Certification

The first parameter is the input string itself, and an optional second parameter is a flag, which specifies how the function should handle quotes.

  • ENT_COMPAT – Default. Only encodes double quotes and leaves single quotes
  • ENT_QUOTES – Encodes both double and single quotes
  • ENT_NOQUOTES – Does not encode any quotes

An optional $encoding third parameter can be passed in. This defines the encoding used when converting characters.

If omitted, as of PHP version 5.6, the default value of the encoding is the default_charset configuration option.

The htmlentities() function is similar to htmlspecialchars() except that it converts all applicable characters to HTML entities.

Zend PHP 7 Certification

It’s worth noting that the default configuration of htmlentities() doesn’t protect you against XSS attacks when using single quotes to define the border of the tag’s attribute-value. XSS is then possible by injecting a single quote. So it is recommended to pass in ENT_QUOTES as the second parameter.

Similar to htmlspecialchars(), an optional $encoding third parameter can be passed in. This will also be the value of the default_charset configuration option if the parameter is omitted as of PHP 5.6.

strip_tags() strips HTML and PHP tags from a string. The first parameter is the input string itself. The second parameter is an allowable list of tags, allowable_tags, not to strip as a string:

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');

// Outputs:
Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

Only non-self-closing tags should be used in allowable_tags. For example, to allow both <br> and <br/>, you should add in the parameter like the below.

strip_tags($string, '<br>')

View the other sections:

Note: This article is based on PHP version 7.0.